Вы можете использовать метод 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