I was trying to test my nestjs application, but i'm not so sure about what kind of test I have to write, I want to test my services, so to test it I'm using the function createTestingModule provided by nestjs, this is my code
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
providers: [DeliveryManService],
imports: [
TypeOrmModule.forFeature([UserRepository, DeliveryManRepository]),
PostgresProviderModule,
],
}).compile();
service = moduleRef.get<DeliveryManService>(DeliveryManService);
});
but unfortunately I was watching other peoples coding and instead of using the typeorm repository directly they are using a mock to do this stuff, So I thought...
Is my test useless ?
Should I write tests only using mock instead of typeorm provider ?
What kind of test did I write ?
EDIT These are my tests:
it('should be defined', () => {
expect(service).toBeDefined();
});
it('should save and return a new delivery man', async () => {
const deliveryMan = await service.preRegister(preRegister);
expect(deliveryMan).toBeDefined();
expect(deliveryMan.id).toBeDefined();
});
it('should return an array of delivery man', async () => {
const deliveryMans = await service.findAll({ page: 1, limit: 100 });
expect(deliveryMans).toBeDefined();
expect(deliveryMans).toBeInstanceOf(Array);
expect(deliveryMans.length).toBeGreaterThanOrEqual(1);
});
CodePudding user response:
If you have tests actually talking to your database you have an integration test, that is testing the integration between your service class and the database. Usually you want to be careful with the number of these because they require a database and usually modify data in that database, meaning you may end up modifying the wrong data if a config is incorrect.
A unit test would end up mocking the database as shown in this repo here. These tests should usually only take a few seconds at most, whereas integration tests can take longer due to having to send data over the wire to make the connection to the database and retrieve the query results.