I'm setting up Jest to test a typescript application.
How do I clear a mocked function and restore the original implementation for other tests?
To mock the function I've used: jest.fn().mockImplementationOnce()
So far I've tried jest.clearAll() / resetModules() / resetAllMocks() in beforeEach as well as afterEach without any success.
app.test.ts
import App from './app';
import { DbService } from './lib/dbService';
describe('App', () => {
let dbService: DbService;
let app: App;
beforeEach(() => {
jest.clearAllMocks();
dbService = new DbService();
app = new App();
});
describe('getUsers', () => {
it('Should get an array users #1', () => {
expect(app).toBeInstanceOf(App);
const allUsers = app.getAllUsers();
expect(allUsers[0].id).toBeDefined();
});
it('should return an error #2', () => {
DbService.prototype.getAllUsers =
jest.fn().mockImplementationOnce(() => {
return new Error('No connection to DB');
});
expect(app.getAllUsers()).toEqual(new Error('No connection to DB'));
});
it('Should get an array users #3', () => {
expect(app).toBeInstanceOf(App);
const allUsers = app.getAllUsers();
expect(allUsers[0].id).toBeDefined();
});
});
});
app.ts
import { DbService } from './lib/dbService';
export default class App {
private dbService: DbService;
constructor() {
this.dbService = new DbService();
}
getAllUsers() {
return this.dbService.getAllUsers();
}
}
lib/dbService.ts
let instance: DbService;
export class DbService {
constructor() {
if (!instance) {
instance = this;
}
return instance;
}
getAllUsers() {
return [
{id: 1, username: 'john'},
{id: 2, username: 'bill'}
]
}
}
I expect test #3 to pass like test #1, but it actually fails with the following error:
FAIL src/app.test.ts
App
getUsers
√ Should get an array users #1 (3ms)
√ should return an error #2 (1ms)
× Should get an array users #3 (1ms)
● App › getUsers › Should get an array users #3
TypeError: Cannot read property '0' of undefined
31 | expect(app).toBeInstanceOf(App);
32 | const allUsers = app.getAllUsers();
> 33 | expect(allUsers[0].id).toBeDefined();
| ^
34 | });
35 | });
36 | });