包含承诺的单元测试功能

时间:2019-05-31 11:15:40

标签: node.js unit-testing promise chai sinon

我有这个功能:

function _init()
{ 
    return _getNetDesc() // this is a promise
    .then(data => {

       // do something
    })  
    .then(() => {

        return _getNetOperation(); // this is a promise
    })
    .then( () =>{
        return _getNetNodeList(); // this is a promise
    }) 

    .catch( e =>
    {
        logger.error("JZW","init",e);

    });
}

为了测试该函数是否抛出,我在mocha/sinon/chai中写道:

it("should throw eception for no GW", async () => {
        _getNetDesc = sinon.stub().throws();
        const test = await jzw.init;
        expect(test).to.be.rejected;

    });

但我知道

 TypeError: [Function: _init] is not a thenable.

1 个答案:

答案 0 :(得分:0)

You're missing to call the function and reject the promise:

it("should throw eception for no GW", async () => {
  _getNetDesc = sinon.stub().returns(Promise.reject(...)); // returns a rejected promise
  const test = await jzw.init(); // call the function to get the promise
  expect(test).to.be.rejected;
});