Jest单元测试一个函数,该函数调用一个返回promise

时间:2017-08-13 18:50:59

标签: javascript unit-testing promise jest

如果我的代码是这样的:

import externalThing from 'externalThing'
import anotherThing from 'anotherThing'

function functionIWantToTest()
{    
    externalThing.doSomething()
    .then(data=>{
        anotherThing.do(data.Id)
    })
}

对此进行单元测试的最佳实践方法是什么?

理想情况下,测试会是这样的:

import externalThing from 'externalThing'
import anotherThing from 'anotherThing'

jest.mock('externalThing',()=>jest.fn())
jest.mock('anotherThing',()=>jest.fn())

describe('when calling functionIWantToTest',()=>{

    beforeEach(()=>{     
       anotherThing.do=jest.fn()
       //mock external thing somehow so that it still the 'then' code

       functionIWantToTest()
    })

    it('anotherThing should be called',()=>{
        expect(anotherThing.do).toHaveBeenCalledWith(1)
    });
});

但是当我尝试时,我最终只使用jest.fn()构建了一系列模拟函数,并且实际上没有代码被执行。

1 个答案:

答案 0 :(得分:1)

尚未尝试jest。您可以使用console.assert()来测试函数调用和返回的Promise值。注意,任何函数调用实际上都没有返回任何值,如果与预期结果有关,请参阅Why is value undefined at .then() chained to Promise?

function functionIWantToTest() {
  return Promise.resolve({
      Id: 1
    })
    .then(data => {
      console.assert(data.Id === 1, data, [`${data.Id} is not equal to 1`]);
      console.assert(data.Id !== 1, data, [`${data.Id} is equal to 1`]);
    })
}

functionIWantToTest()