[英]Jest test the resolve reject callback
我有此函数,它为api调用调用util函数。 util函数根据api结果解析或拒绝。
现在,我需要对具有以下结构的回调函数进行单元测试。
`theClassMethod : () => {
return utilMethod().then(
result => { this.functionOne() //Test this function is called },
error => { this.functionTwo() //Test this function is called }
)
}`
util方法返回一个promise,如下所示:
utilFunc = (data :string) :Promise<ResultData[]> => {
return new Promise(async (resolve, reject) => {
try{
resolve(data)
}catch{
reject(error)
}
})
}
https://codesandbox.io/s/vjnwy1zw75?fontsize=14
我试过的
我花了很多时间寻找类似的问题。 这里的大多数问题是要测试代码,例如:
theClassMethod : () => { utilMethod.then().catch()}
我正在尝试解决的问题是测试解决方案,然后在then块then(function1, function2)
拒绝回调。 必须测试function1内部的代码块是否调用了某些预期的函数。
您正在描述的方法( utilMethod
来解决/拒绝)是一种很好的方法。
这是一个简单的工作示例,可以帮助您入门:
注意 :我将functionOne
作为类方法实现,并将functionTwo
作为实例属性实现,以展示如何监视两种类型的函数:
util.js中
export const utilMethod = async () => 'original';
code.js
import { utilMethod } from './util';
export class MyClass {
functionOne() { } // <= class method
functionTwo = () => { } // <= instance property
theClassMethod() {
return utilMethod().then(
result => { this.functionOne() },
error => { this.functionTwo() }
);
}
}
code.test.js
import { MyClass } from './code';
import * as util from './util';
test('theClassMethod', async () => {
const mock = jest.spyOn(util, 'utilMethod');
const instance = new MyClass();
const functionOneSpy = jest.spyOn(MyClass.prototype, 'functionOne'); // <= class method
const functionTwoSpy = jest.spyOn(instance, 'functionTwo'); // <= instance property
mock.mockResolvedValue('mocked value'); // <= mock it to resolve
await instance.theClassMethod();
expect(functionOneSpy).toHaveBeenCalled(); // Success!
mock.mockRejectedValue(new Error('something bad happened')); // <= mock it to reject
await instance.theClassMethod();
expect(functionTwoSpy).toHaveBeenCalled(); // Success!
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.