This question already has answers here:
Bluebird Each loop in Mocha not working
                                
                                    (2个答案)
                                
                        
                                3年前关闭。
            
                    
我是JavaScript测试框架的新手。我想做一些优化,但是遇到一些问题。该项目正在使用should.js

这是我原始测试用例的简化版本:

describe('Simple', function() {
  describe('Test', function() {
    it('should do something', function(done) {
      somePromise.then(function(data) {
        data.should.above(100);
        done();
      });
    }

    it('should do something else but alike', function(done) {
      somePromise.then(function(data) {
        data.should.above(100);
        done();
      });
    }

  }
});


我正在尝试通过这种方式:

var testFunc = function(data) {
  it('should do something', function(done) {
      data.should.above(100);
      done();
  });
}

describe('Simple', function() {
  describe('Test', function() {
      somePromise.then(function(data) {
        testFunc(data);
      });

      somePromise.then(function(data) {
        testFunc(data);
      });
  }
});


承诺是异步的,也许这就是为什么我的“优化”无法正常工作的原因?我在文档中没有找到describe函数的“完成”回调。

提前致谢!任何帮助将不胜感激!

最佳答案

您的示例不起作用since Mocha has finished registering test cases when your promise resolves

用不同的断言测试相同的诺言

要使用多个断言测试一个promise,您只需要在测试开始时创建promise,然后在如下所示的it块中使用它:

describe('A module', function() {
    var promise;

    before(function () {
        promise = createPromise();
    });

    it('should do something', function() {
        return promise.then(function (value) {
            value.should.be.above(100);
        });
    });

    it('should do something else', function() {
        return promise.then(function (value) {
            value.should.be.below(200);
        });
    });
});


请注意,如果从API调用返回了promise,则该调用将只进行一次。 The result is simply cached in the promise for the two test cases.

这还利用了you can return promises from test cases而不是使用完成的回调的事实。如果承诺被拒绝或then()调用中的任何断言失败,则测试用例将失败。

使用相同的断言测试不同的Promise

假设您要使用相同的断言测试不同的Promise,可以将一个函数传递给testFunc,该函数创建要测试的Promise。

var testFunc = function(promiseFactory) {
  it('should do something', function(done) {
      promiseFactory().then(function(data) {
          data.should.above(100);
          done();
      });
  });
}

describe('Simple', function() {
  describe('Test', function() {
      testFunc(function () { return createSomePromise(); });

      testFunc(function () { return createSomeOtherPromise(); });
  });
});


由于Mocha的it函数在describe块内立即运行,因此可以使用。在实际运行测试用例时,然后使用promiseFactory回调创建承诺。

您也可以return promises from test cases更改testFunc以返回断言作为promise,如下所示:

var testFunc = function(promiseFactory) {
  it('should do something', function() {
      return promiseFactory().should.eventually.be.above(100);
  });
}

关于javascript - 使用异步功能的Mocha/Should.js ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37416234/

10-12 02:46
查看更多