ожидать (jest.fn ()). toHaveBeenCalledWith (... ожидается) - PullRequest
0 голосов
/ 25 февраля 2020

Я пытаюсь написать модульный тест для контроллера, который написан в NEST. JS Ниже приведен метод входа, для которого не выполняется модульный тест

@Post('login')
async login(@Body() payload: LoginPayload): Promise<any> {
    this.logger.info("Calling Loging");
    this.logger.debug("Calling Loging");
    const user = await this.authService.validateUser(payload);
    return await this.authService.createToken(user);
}

Модульный тест для приведенного выше кода написано в JEST Framework.

  beforeEach(async () => {
    // createInputDetails() Functions initializes the LoginPayload, RegisterPayload and User Object
    createInputDetails();
    module = await Test.createTestingModule({
      controllers: [AuthController],
      providers: [
        {
          provide: AuthService,
          useFactory: () => ({
            createToken: jest.fn(() => true),
            validateUser: jest.fn(() => true),
          }),
        },
        {
          provide: UserService,
          useFactory: () => ({
            get: jest.fn(() => true),
            getByEmail: jest.fn(() => true),
            getByEmailAndPass: jest.fn(() => true),
            create: jest.fn(() => true),
          }),
        },
      ],
    }).compile();

    controller = module.get<AuthController>(AuthController);
    authService = module.get<AuthService>(AuthService);
    userService = module.get<UserService>(UserService);
  });

  describe('login', () => {
    it('should validate user', async () => {
      controller.login(loginPayload);
      expect(authService.validateUser).toHaveBeenCalledWith(loginPayload);
      expect(authService.createToken).toHaveBeenCalledWith(user);
    })
  })

И я получаю следующую ошибку. Нужно знать, чего мне здесь не хватает?

expect(jest.fn()).toHaveBeenCalledWith(...expected)
    Expected: {"email": "abc@xyz.com", "firstName": "abc", "lastName": "pqr", "password": "Test@1234", "profile": {"age": 32, "nickname": "abc"}, "userId": 14}

    Number of calls: 0

       96 |       controller.register(registerPayload);
       97 |       // expect(userService.create).toHaveBeenCalledWith(registerPayload);
    >  98 |       expect(authService.createToken).toHaveBeenCalledWith(user);
          |                                       ^
       99 |     })
      100 |   })
      101 | 

      at Object.it (modules/auth/auth.controller.spec.ts:98:39)

1 Ответ

0 голосов
/ 25 февраля 2020

Ваш controller.login метод является асинхронным, поэтому вы должны быть await controller.login(registerPayload), а не вызывать его напрямую. У меня такое чувство, что вы, шутка, не ожидаете обработки nextTick и движетесь дальше, не позволяя методу контроллера запустить свой сегмент

...