I would like to unittest corner cases for my TypeORM database calls. I have already mocked all my TypeORM repositories with valid data. But I would like to SpyOn the repository and change the return value form TypeORM. How do I do that?
import {INestApplication} from '@nestjs/common';
import {Test} from '@nestjs/testing';
import {CommonModule} from '@src/common/common.module';
import {AuthService} from './auth.service';
import {Repository} from 'typeorm';
import {V3User} from '@src/database/entity/user.v3entity';
describe('AuthService', () => {
let service: AuthService;
let app: INestApplication;
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [CommonModule.forRoot(`${process.env.DEV_ENV}`)],
providers: [
AuthService,
{provide: 'V3USER_REPOSITORY', useValue: mockRepositoryV3User()},
],
}).compile();
app = module.createNestApplication();
await app.init();
service = module.get<AuthService>(AuthService);
});
it('test auth service - with non existing user in v3 db', async () => {
jest.spyOn(?????? , 'findOne').mockImplementation(() => undefined);
const res = await service.loginUser("bad token");
await expect(service.tokenBasedAuth('example bad token'))
.rejects.toThrow('bad token exception');
});
});
I mock the database like this for normal test cases:
export const mockRepositoryV3User = () => ({
metadata: {
columns: [],
relations: [],
},
findOne: async () =>
Promise.resolve({
id: 3,
email: '[email protected]',
first_name: 'david',
last_name: 'david',
last_login: '2019-07-15',
date_joined: '2019-07-15',
}),
});