Skip to content

12_Unit Testing

Moritzjenny edited this page Jan 27, 2023 · 5 revisions

We use Jest for unit testing in both frontend and backend.

The nomenclature for test files is as follows: <filename>.spec.ts. Thus, the test file for user.resolver.ts would be named user.resolver.spec.ts, and would be located in the same folder.

In testing, we generally follow Jest's suggested approach. Tests are grouped in describe blocks that should have a descriptive name.

describe('UserResolver', () => {
  
  beforeEach(async () => {
    <things to execute before every test>
  });

  <tests go here>
}

Each test is then structured as follows:

it('should do something'), async () => {
  <test contents go here>
}

Tests and test groups should have descriptive names, so in case of test failure in e.g. an automated GitHub action, it's easy to determine what went wrong.

Examples

To test resolvers we can mock services a mock factory in order to narrow down the scope of the test. To create the mocks we can use the TestingModule from @nestjs/testing. We orient ourselves on the testing documentation of the NestJS framework.

Testing a resolver

A exemplary test to for a resolver could look like this.

beforeEach(async () => {

    const module: TestingModule = await Test.createTestingModule({
      controllers: [UserResolver],
      providers: [
        // Provide your mock instead of the actual repository
        {
          provide: getRepositoryToken(User),
          useFactory: repositoryMockFactory,
        },
      ],
    })
      .useMocker((token) => {
        if (token === UserService) {
          return {
            // Mock the method in the service
            getMyUser: jest.fn().mockResolvedValue(user),
          };
        }
      })
      .compile();

    // Get the mocks
    userService = module.get(UserService);
    userResolver = module.get(UserResolver);
    userRepository = module.get(getRepositoryToken(User));
  });