Javascript Jest单元测试调用返回承诺的函数的函数
如果我有这样的代码:Javascript Jest单元测试调用返回承诺的函数的函数,javascript,unit-testing,promise,jestjs,Javascript,Unit Testing,Promise,Jestjs,如果我有这样的代码: import externalThing from 'externalThing' import anotherThing from 'anotherThing' function functionIWantToTest() { externalThing.doSomething() .then(data=>{ anotherThing.do(data.Id) }) } import externalThing fr
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)
});
});
单元测试的最佳实践方法是什么
理想情况下,测试应如下所示:
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()构建了一系列模拟函数,实际上没有执行任何代码。没有尝试过jest。您可以使用
console.assert()
测试函数调用和Promise
返回的值。注意,两个函数调用都没有实际返回值,如果这与预期结果有关,请参阅
函数functionIWantToTest(){
还愿({
身份证号码:1
})
。然后(数据=>{
assert(data.Id==1,data,[`${data.Id}不等于1`]);
assert(data.Id!==1,data,[`${data.Id}等于1`]);
})
}
functionIWantToTest()
调用functionIWantToTest()
的预期结果是什么?Hey@guest271314它在测试中:),用于另一件事。是否使用参数调用了。未尝试jest
。jest.fn()返回什么?是否有两种不同的值分配给另一个对象。是否执行?请注意,实际上没有从functionIWantToTest()
calljest.fn()
返回模拟函数返回值,您可以通过执行jest.fn(()=>{…})
来提供模拟实现。是的,这是一个void函数,我希望它调用其他东西(真实代码中有更多的逻辑)好的。尽管调用functionIWantToTest()
仍然没有返回任何值。如果另一个东西
是一个在中已定义的函数,那么您为什么要从“另一个东西”导入另一个东西
?