coffee-and-doughnuts / realworld-nestjs

Implementation of RealWorld project written in NestJs
MIT License
0 stars 0 forks source link

TDD; Build an environment for testing. #2

Open nyeong opened 1 year ago

nyeong commented 1 year ago

See also NestJS.

Unit Tests

E2E Tests

nyeong commented 1 year ago

Unit Test Example

Let's use UserService as an example.

UserService dependence on Repository<User> and JwtService. Mockup those.

const mockRepository = {
  findOneBy: jest.fn(),
  save: jest.fn(),
  // ...
}

Inject dependencies using mockups.

describe('UserService', () => {
  let service: UserService;
  let repository: Repository<User>;
  beforeEach(async () => {
    const moduleRef: TestingModule = await Test.createTestingModule({
      providers: [
        UserService,
        { // use `mockRepository` value instead of `Repository<User>`
          provide: getRepositoryToken(User), 
          useValue: mockRepository
        }
      ],
    }).compile();

    service = moduleRef.get(UserService);
    repository = moduleRef.get(Repository<User>)
  });
});

And test whether the function is called using jest.spyOn function.

describe('create', () => {
  it('should create a user with proper input', async () => {
    const spySave = jest.spyOn(repository, 'save')

    const createDto = new CreateDto({
      email: "email@example.com",
      username: "example",
      password: "rootme"
    })
    service.create(createDto)

    expect(spySave).toBeCalled()
  })

  it.todo('should throw an error if the given email already taken');
});