Answer the question
In order to leave comments, you need to log in
How to use a test base (not the main one) in NetsJS with TypeORM in unit tests?
Greetings.
Before running the tests, I start the connection to the test database:
beforeEach(() => {
return createConnection({
type: "sqlite",
database: 'testBase",
entities: [User, SmsCodes],
...........
});
afterEach(() => {
let conn = getConnection();
return conn.close();
});
it('Возврат: true при правильном коде SMS', async () => {
const usersService = UsersService;
await getRepository(SmsCodes).insert({
email: '[email protected]',
code: 1234,
});
const checkCorrectSms = await usersService.checkCorrectSmsCode('[email protected]', 1234);
// Та самая тестируемая функция
expect(checkCorrectSms).toBe(true);
})
Answer the question
In order to leave comments, you need to log in
I figured it out, here's the solution for anyone who needs it:
You need to pass the test repository to the service constructor, where this function is declared.
describe('Users Service Test /services/users.service.ts', () => {
let usersService: UsersService;
let smsCodesRepository: Repository<SmsCodes>;
let testingModule: TestingModule;
const testConnectionName = 'testConnection';
beforeEach(async () => {
testingModule = await Test.createTestingModule({
providers: [
UsersService,
{
provide: getRepositoryToken(SmsCodes),
useClass: Repository,
},
],
}).compile();
let connection = await createConnection({
type: "postgres",
database: "baseTest",
dropSchema: true,
entities: [SmsCodes],
synchronize: true,
name: testConnectionName
});
smsCodesRepository = getRepository(SmsCodes, testConnectionName);
usersService = new UsersService(userRepository, smsCodesRepository);
return connection;
});
afterEach(async () => {
await getConnection(testConnectionName).close()
});
describe('checkCorrectSmsCode', () => {
it('Возврат: true при правильном коде SMS', async () => {
const mockEmail = '[email protected]'
const mockCode = 1234;
await smsCodesRepository.insert({
email: mockEmail,
code: mockCode,
});
const checkCorrectSms = await usersService.checkCorrectSmsCode(mockEmail, mockCode);
expect(checkCorrectSms).toBe(true);
})
})
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question