我遇到一种情况,我想测试在if
语句中调用的函数。我不知道如何测试实际上返回boolean
的函数。
代码
function test(){
if(await SOP3loginConfig(props: object).isSOP3()){
//calls if statements
} else {
//calls else statements
}
}
在上面的代码段中,我正在尝试测试该功能,我能够做到这一点,但是可以通过if()
分支。
我正在使用jest
和react-testing-library
。
我无权访问if
语句中的函数主体。
尝试过
it('Should call the SOP3 functions', () => {
props.user = {};
let SOP3loginConfig = (props: any) => {
console.log(' ========================= I A M A TEST');
return {
isSOP3: () => {
console.log(' ================ iSOP3 called');
return true;
},
};
};
functions.start(props);
expect(SOP3loginConfig(props).isSOP3()).toHaveBeenCalled();
expect(props.history.push).not.toHaveBeenCalled();
});
但是出现了这个错误!
expect(received).toHaveBeenCalled()
Matcher error: received value must be a mock or spy function
Received has type: boolean
Received has value: true
229 | };
230 | functions.start(props);
> 231 | expect(SOP3loginConfig(props).isSOP3()).toHaveBeenCalled();
| ^
232 | expect(props.history.push).not.toHaveBeenCalled();
233 | });
234 |
答案 0 :(得分:1)
尝试使用jest.fn
it('Should call the SOP3 functions', () => {
props.user = {};
const isSOP3Mock = jest.fn(() => {
console.log(' ================ iSOP3 called');
return true;
})
let SOP3loginConfig = (props: any) => {
console.log(' ========================= I A M A TEST');
return {
isSOP3: isSOP3Mock,
};
};
functions.start(props);
expect(isSOP3Mock).toHaveBeenCalled();
expect(props.history.push).not.toHaveBeenCalled();
});
假设functions.start(props)
将调用您的test
函数。