I have the following integration test written in nestJs with jest:
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken, TypeOrmModule } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RefreshTokenEntity } from '../refresh-token/refresh-token.entity';
import { UserEntity } from './user.entity';
import { UsersService } from './users.service';
describe('UsersService', () => {
let service: UsersService;
let userRepository: Repository<UserEntity>;
let module: TestingModule;
beforeAll(async () => {
module = await Test.createTestingModule({
imports: [
TypeOrmModule.forRootAsync({
useFactory: () => ({
type: 'better-sqlite3',
name: 'test-db-sqlite',
database: ':memory:',
dropSchema: true,
entities: [UserEntity, RefreshTokenEntity],
synchronize: true,
}),
}),
TypeOrmModule.forFeature([UserEntity]),
],
providers: [UsersService],
}).compile();
service = module.get<UsersService>(UsersService);
userRepository = module.get<Repository<UserEntity>>(
getRepositoryToken(UserEntity),
);
});
it('should find all users', async () => {
const user1: UserEntity = new UserEntity();
user1.username = 'test-user';
user1.password = 'password';
user1.isActive = true;
await userRepository.save(user1);
const users: UserEntity[] = await service.findAll();
expect(users).toHaveLength(1); // pass
});
it('should find no users', async () => {
const users: UserEntity[] = await service.findAll();
expect(users).toHaveLength(0); // fail, user is still saved from previous test
});
});
Between each test, I want to revert the in-memory DB back to a completely clean state, I've tried doing this via userRepository.query("DROP table users"); this works, but it won't work for future tests where foreign keys are involved.
Thanks in advance!