1

我有以下形式的代码:

sut.methodtotest = param => {
    return dependency.methodcall(param)
        .then((results) => {
            return results;
        });
};

我想测试 sut.methodtotest,但是当我使用 chai、mocha、require、sinon 和 Javascript 社区可以使用的众多其他框架时,我收到一条错误消息:

dependency.methodcall(...).then is not a function

我的问题是:我如何模拟dependency.methodcall,以便它返回一些模拟数据并且'then'函数可用?

我的测试代码看起来像这样

describe("my module", function() {
    describe("when calling my function", function() {

        var dependency =  require("dependency");

        var sut =  proxyquire("sut", {...});

        sut.methodtotest("");

        it("should pass", function() {

        });
    });
});
4

2 回答 2

1

我正在使用茉莉间谍来实现这一目标:

beforeEach(function() {
    //stub dictionary service
    dictionaryService = {
        get: jasmine.createSpy().and.callFake(function() {
            return { then: function(callback) {
                return callback(/*mocked data*/);
            } };
        })
    };
});

it('should call dictionary service to get data', function () {
    expect(dictionaryService.get).toHaveBeenCalledWith(/*check mocked data*/);
});
于 2017-01-11T14:38:37.530 回答
1

我使用sinon的沙箱,像这样

var sandbox = sinon.sandbox.create();
var toTest = require('../src/somemodule');

describe('Some tests', function() {
  //Stub the function before each it block is run
  beforeEach(function() {
    sandbox.stub(toTest, 'someFunction', function() {
      //you can include something in the brackets to resolve a value 
      return Promise.resolve();  
    });
  });
  
  //reset the sandbox after each test
  afterEach(function() {
    sandbox.restore();  
  });
  
  it('should test', function() {
    return toTest.someFunction().then(() => {
      //assert some stuff                                  
    });
  });
});

您应该return在 then 块中断言,例如chai

return toTest.someFunction().then((result) => {
    return expect(result).to.equal(expected);                
});

如果您有任何其他问题,请发表评论。

于 2017-01-11T14:29:29.097 回答