Javascript Jest单元测试函数,它调用第二个返回承诺的函数
已编辑问题,并应用了vazsonyidl建议 我必须为与此类似的函数编写单元测试:Javascript Jest单元测试函数,它调用第二个返回承诺的函数,javascript,typescript,unit-testing,testing,jestjs,Javascript,Typescript,Unit Testing,Testing,Jestjs,已编辑问题,并应用了vazsonyidl建议 我必须为与此类似的函数编写单元测试: import {External} from 'ExternalModule'; async functionA(){ this.functionB().then((data) => { External.functionC(options); console.log("Reached1"); }).catch((data) =>
import {External} from 'ExternalModule';
async functionA(){
this.functionB().then((data) => {
External.functionC(options);
console.log("Reached1");
}).catch((data) => {
const { OnError = "" } = data || {}
if(OnError) {
External.functionC(anotherOptions);
console.log("Reached2");
}
})
}
functionB() {
return new Promise(() => {
});
}
由于functionC属于另一个模块,我在\u mocks\u
文件夹中放置了它的模拟:
//_mocks_/ExternalModule.ts
export var External: ExternalClass = {
functionC(){}
}
class ExternalClass{
constructor(){};
functionC(){};
}
我以两种不同的方式模拟了函数B,用于测试然后和捕获:
it("should test then block", () => {
functionB = jest.fn(() => {return Promise.resolve()});
const functionSpy = jest.spyOn(ExternalModule.External, 'functionC');
void functionA().then(() => {
expect(functionSpy).not.toHaveBeenCalled();
});
})
it("should test catch block", () => {
const err = { OnError: "Error" };
functionB = jest.fn(() => {return Promise.reject(err)});
const functionSpy = jest.spyOn(ExternalModule.External, 'functionC');
void functionA().then(() => {
expect(functionSpy).not.toHaveBeenCalled();
});
})
我试图做的是期望functionC被调用并使用正确的参数调用,但是即使我测试functionC是否未被调用,测试也总是通过
我做错了什么?我认为当这个函数捕获错误时,这个错误应该有一个“OnError”属性,这样functionC就可以运行了
const { OnError = "" } = data || {}
if(OnError) {
ExternalClass.functionC(anotherOptions);
}
将响应错误数据更改为返回承诺。拒绝({OnError:'404'})
可以解决此问题。因为您没有向类提供它。
以下代码适用于我:
A类{
异步函数(){
this.functionB().then((数据)=>{
this.functionC();//这里将记录aaa,您需要这个。
}).catch((数据)=>{
常量{OnError=''}=数据| |{};
if(OnError){
console.log('onerror');
}
});
}
函数b(){
返回新承诺(()=>{
});
}
函数c(){
返回2;
}
}
描述('a',()=>{
它('test',()=>{
常数a=新的a();
a、 functionB=jest.fn(()=>Promise.resolve());
const functionBSpy=jest.spyOn(a,“functionC”);
void a.functionA()。然后(()=>{
期望(功能比)。已被调用的时间(1);
});
});
});代码>Jest在执行断言之前不会等待异步代码完成。
您可以使用以下功能:
const waitForPromises = () => new Promise(setImmediate);
迫使Jest在继续之前等待承诺完成:
it("does something", async () => {
promiseCall();
await waitForPromises();
expect(something).toBe(something)
});
对不起,忘了提了。拒绝承诺时,对象err包含OnError属性。调试时,FunctionC已到达,但jest一直告诉我它没有到达。编辑了问题。为了简单起见,我没有将函数B粘贴到这里,但它存在并返回一个承诺,就像您在那里做的一样。调试时,functionC已到达,但jest一直告诉我它没有到达。我将用更多细节更新问题。问题已更新,因为您没有在函数调用上设置间谍。我会在一分钟内回复你的答案。更新答案。好的,我完全理解你的问题。所以你的函数不是synchoronus调用。你需要相应地处理这个问题。如果它是异步的(我认为应该是异步的),那么现在您可以在then回调中处理您的断言。用完整的工作代码更新答案。这解决了问题,谢谢!虽然我在一个类似的函数中遇到了同样的问题,但只有在运行文件的所有测试用例时才会遇到。如果我只运行这一个,它就会通过。有什么想法吗?@RicardoCardoso我相信这可能与mocks有关。有吗?您可以在每次(()=>{jest.restoreAllMocks();})之后实现一个代码>在第一个描述中。因此,如果mock是罪魁祸首,那么在每次测试之后,它们都会被重置。