Unit testing Jest模拟函数调用不计算在内
我想模拟一个对象的函数post。我是这样做的:Unit testing Jest模拟函数调用不计算在内,unit-testing,mocking,jestjs,Unit Testing,Mocking,Jestjs,我想模拟一个对象的函数post。我是这样做的: jest.mock('../../api.js',()=>{ return()=>{ 返回{ 帖子:jest.fn(()=>{ log('调用了POST!'); 返回承诺。解决(); }), }; }; }); 然后,我提出我的要求: const-api=require('../../api'); 最后,我调用我的服务,它将从api模块调用post()函数: client.doPost() .然后(()=>{ log('count:',api(
jest.mock('../../api.js',()=>{
return()=>{
返回{
帖子:jest.fn(()=>{
log('调用了POST!');
返回承诺。解决();
}),
};
};
});
然后,我提出我的要求:
const-api=require('../../api');
最后,我调用我的服务,它将从api
模块调用post()
函数:
client.doPost()
.然后(()=>{
log('count:',api().post.mock.calls.length);
expect((api().post)).toBeCalled();
});
doPost()
函数调用模拟的post()
one('post was called!')消息,但计数等于0,expect失败。这需要检查,但我猜您在api()中访问的变量.post.mock.calls.length
调用与client.doPost()调用中使用的调用不同
实际上,当调用api()
时,mock在每次调用时都会返回一个新对象
您要做的是将存根存储在专用变量中,并在then()测试中访问它:
const postStub = jest.fn(() => {
console.log('POST was called !');
return Promise.resolve();
});
jest.mock('../../apis.js', () => {
return () => {
return {
post: postStub,
};
};
});
然后使用它(当然应该在同一个文件中):
变通办法
global.iPost=0;
jest.mock('../../apis.js', () => {
return () => {
return {
post: jest.fn(() => {
console.log('POST was called !');
global.iPost++;
return Promise.resolve();
}),
};
};
});
expect(global.iPost).toEqual(1)
jest.mock()
不允许引用任何范围外的变量。无效的变量访问:postStub
global.iPost=0;
jest.mock('../../apis.js', () => {
return () => {
return {
post: jest.fn(() => {
console.log('POST was called !');
global.iPost++;
return Promise.resolve();
}),
};
};
});
expect(global.iPost).toEqual(1)