I need to mock the function of a dependency but only for a specific test case. In my other tests, I want to leave the module as is. I am also mocking other modules. Those need to stay mocked.
I tried multiple approaches as many variants of this question have been asked, but due to my need to use the original module when not mocked, none of the other solutions seem to work...
Here's an example of what I would need
// app.ts
import * as moduleA from 'moduleA';
// ...
app.post('/signup', async (req, res) => {
// ...
const hashed = await moduleA.hash(req.body.password);
// ...
});
export default app;
// app.test.ts
// some mocks
jest.mock('./database', () => ({ ... }));
// ...
import * as request from 'supertest';
import app from './app';
// ...
describe('A', () => {
test('Those should work', async () => {
const response = await request(app).post('/signup').send({ password: 'pw' });
expect(response.status).toBe(200);
// ...
});
// many other tests
test('I need to force hash to crash here', async () => {
// mock moduleA.hash only for this test
const response = request(app).post('/signup').send({ password: 'pw' });
expect(response.status).toBe(500);
});
test('moduleA.hash should be back to its default function', async () => {
// request(app) and moduleA.hash will work properly, not mocked
// ./database stays mocked
});
});