javascript - Jest spyOn 仅在第二次调用和第三次调用时模拟实现
问题描述
我有一个函数,我只想在第二次调用和第三次调用时模拟,但在第一次调用时使用默认实现。我查看了 Jest 文档,并且有一个函数 mockImplementationOnce 可以用来模拟单个调用的实现。
有没有我可以使用的函数,它会在第一次调用时使用默认实现,并且只模拟第二次和第三次调用?
let functionCalls = 0;
const database = {
fetchValues() {
fetchValues();
fetchValues();
},
};
jest.spyOn(database, 'fetchValues')
.useDefaultImplementation() // <-- is there such a function?
.mockImplementationOnce(() => 42)
.mockImplementationOnce(() => 42)
解决方案
您可以使用mockImplementation
方法来模拟默认实现。查看模拟实现
例如
const database = {
fetchValues() {
return 'real data';
},
};
describe('61450440', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should pass', () => {
jest
.spyOn(database, 'fetchValues')
.mockImplementation(() => 'default')
.mockImplementationOnce(() => 'first call')
.mockImplementationOnce(() => 'second call');
console.log(
[database.fetchValues(), database.fetchValues(), database.fetchValues(), database.fetchValues()].join(','),
);
});
it('should pass too', () => {
jest
.spyOn(database, 'fetchValues')
.mockImplementation(() => 'real data')
.mockImplementationOnce(() => 'real data')
.mockImplementationOnce(() => 'first call')
.mockImplementationOnce(() => 'second call');
console.log(
[database.fetchValues(), database.fetchValues(), database.fetchValues(), database.fetchValues()].join(','),
);
});
it('should pass 3', () => {
const fetchValuesSpy = jest.spyOn(database, 'fetchValues');
console.log('call original fetchValues:', database.fetchValues());
fetchValuesSpy.mockImplementationOnce(() => 'first call').mockImplementationOnce(() => 'second call');
console.log('call mocked fetchValues:', database.fetchValues(), database.fetchValues());
console.log('call original fetchValues again:', database.fetchValues());
});
});
试验结果:
PASS stackoverflow/61450440/index.test.ts (13.748s)
61450440
✓ should pass (20ms)
✓ should pass too (1ms)
✓ should pass 3 (12ms)
console.log stackoverflow/61450440/index.test.ts:15
first call,second call,default,default
console.log stackoverflow/61450440/index.test.ts:27
real data,first call,second call,real data
console.log stackoverflow/61450440/index.test.ts:34
call original fetchValues: real data
console.log stackoverflow/61450440/index.test.ts:36
call mocked fetchValues: first call second call
console.log stackoverflow/61450440/index.test.ts:37
call original fetchValues again: real data
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 15.761s
推荐阅读
- java - 通过 WebDriverManager 使用 Selenium 时如何修复 java.net.UnknownHostException: npm.taobao.org
- clickhouse - 我可以在 quantilesExact 中使用 0 和 1 值吗
- node.js - 使用 NodeJS 验证输入以接受所有语言的字母数字
- ios - SwiftUI 中的数据关联
- vue.js - vue.js 中的复选框选择问题
- python - 使用 python 和 babel 获取翻译的国籍名称列表(或者其他什么?)
- xcode - 如何在 xcode 中添加启动图像?
- sql - IF 等于或子句
- wordpress - 带有千位分隔符和小数位分隔符的 Woocommerce 小部件自定义价格
- snowflake-cloud-data-platform - 雪花从修改的行返回数据