mockImplementation, mockReturnValue, mockResolvedValue, mockRejectedValue有什么区别?
mockImplementation
接受用来mock的实现函数。mock本身仍然会记录所有进入的调用和来自自身的实例 —— 唯一的区别是,当模拟被调用时,实现也将被执行。
遇到function是第三方库的异步任务,则使用mockImplementation来模拟异步结束后的回调。
例如unzip()的回调,我们用mockImplementation模拟回调
// component.ts
import { unzip } from 'fflate';
unzip(new Uint8Array(buffer), (err, unzipped) => {
if (err) {
console.log(err.message);
resolve(undefined);
} else {
resolve(true);
}
});
// spec.ts
const unzippedData = {
'file1.txt': new Uint8Array([1, 2, 3]),
'file2.txt': new Uint8Array([4, 5, 6])
};
const errorMessage = {
message: 'unzip error'
};
const unzipMock = jest.fn().mockImplementation((buffer, callback) => {
callback(errorMessage, unzippedData);
});
const logSpy = jest.spyOn(console, 'log');
jest.spyOn(fflate, 'unzip').mockImplementation(unzipMock);
expect(logSpy).toBeCalledWith('unzip error');
mockReturnValue
接受每当调用 mock 函数时将返回的值。也就是每当调用mock函数时,他都会返回我们给定mockReturnValue的值
const mock = jest.fn();
mock.mockReturnValue(42);
mock(); // 42
mock.mockReturnValue(43);
mock(); // 43
它是jest.fn().mockImplementation(() => value);的缩写
mockResolvedValue
在异步测试中模拟异步函数非常有用
进入异步方法的then回调
// component.ts
public handleUpload() {
this.decompress();
}
public decompress() {
this.http.get(`/timezones`).then((userId) => {
return true
})
}
// spec.ts
const decompressSpy = jest.spyOn(component, 'decompress')
decompressSpy.mockResolvedValue(true);
await component.handleUpload();
expect(decompressSpy).toBeCalledTimes(1)
mockRejectedValue
mock场景:进入异步方法的catch回调
代码跟mockResolvedValue差不多
mockReturnValueOnce(value)
用于对mock函数的连续调用返回不同的值
//component.ts
public func2(value) {
const result = ...;
return result
}
public function1() {
return this.func2(val2) || this.func2(val2)
}
//spec.ts
jest.spyOn(component.func2).mockReturnValueOnce(true).mockReturnValueOnce(false);
const result = component.function1();
expect(result).tobe(false)