I have a mock prisma service in the the __mocks__
folder and am using it in unit tests like this, which works as expected.
// __mocks__/prisma.service.ts
@Injectable()
export class PrismaService {
foo = {
findUnique: jest.fn().mockResolvedValue({ name: 'foo-mock' })
}
}
// foo.service.spec.ts
jest.mock('path/to/prisma.service.ts');
...
it('', async () => {
const actual = await fooService.findOne(123);
expect(actual).toEqual({ name: 'foo-mock' });
});
it('', async () => {
jest.spyOn(prismaService.foo, 'findUnique').mockResolvedValue({ name: 'foo-spy' });
const actual = await fooService.findOne(123);
expect(actual).toEqual({ name: 'foo-spy' });
});
However, when I do this in an e2e test, the implementation in mocks doesn’t get overridden with the spyOn like it does in unit tests.
// foo.service.e2e-spec.ts
jest.mock('path/to/prisma.service.ts');
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [AppModule]
}).compile();
app = module.createNestApplication();
await app.init();
prismaServie = app.get<PrismaService>(PrismaService);
});
// Fails because name is still 'foo-mock'
it('', () => {
jest.spyOn(prismaService.foo, 'findUnique').mockResolvedValue({ name: 'foo-spy' });
return request(app.getHttpServer())
.get('/foo/123')
.expect(({ body }) => {
expect(body).toEqual({ name: 'foo-spy' })
});
});
Why does it not behave the same as in the unit tests?