Expect(spiedMethod).not.toBeCalled()失败,因为它正在被另一个测试调用

时间:2019-02-15 08:04:44

标签: node.js unit-testing jestjs nestjs

我一直在尝试用测试覆盖我们的代码库。我正在将jestNestJS一起使用。 这是登录方法。

  public async login(
    @Body() loginDto: DUserLoginRequest,
  ): Promise<DResponse<DLoginResponseV2>> {
    const user: User = await this.userService.verifyCredentials(
      loginDto.login,
      loginDto.password,
    );

    let userTransformed = new DUser(user);
    let accessToken: string = await this.authService.generateUserAccessToken(
      user,
    );

    return new DResponse<DLoginResponseV2>(
      'Successfully logged in',
      new DLoginResponseV2(userTransformed, accessToken),
    );
  }
如果提供的电子邮件或密码错误,

UserService.verifyCredentials()会抛出UnauthorizedException

这是我的测试用例。

  describe('login', () => {
    it('should return user details on successfull login', async () => {
      let loginPayload: DUserLoginRequest = {
        login: 'sayantan.das@codelogicx.com',
        password: 'sayantan94'
      };

      let dUser = new DUser(user);

      let response = new DResponse<DLoginResponseV2>(
        'Successfully logged in',
        new DLoginResponseV2(dUser, 'access_token')
      );

      expect(await userController.login(loginPayload)).toEqual(response);
      expect(userService.verifyCredentials).toBeCalled();
      expect(userService.verifyCredentials).toBeCalledWith(loginPayload.login, loginPayload.password);

      expect(authService.generateUserAccessToken).toBeCalled();
      expect(authService.generateUserAccessToken).toBeCalledWith(user);
      expect(authService.generateUserAccessToken).toReturnWith('access_token');
    });

    it('should throw UnauthorizedException if wrong email or password is provided', async () => {
      let loginPayload = {
        login: 'wrongemail@gamil.com',
        password: 'wrongpassword'
      } as DUserLoginRequest;

      await expect(userController.login(loginPayload)).rejects.toThrow(UnauthorizedException);

      // this assertion fails. but works all right if the successful login test case is removed 
      await expect(authService.generateUserAccessToken).not.toBeCalled();
    });
  });

但是这个测试用例失败了

FAIL  src/modules/user/user.controller.spec.ts
  ● User Controller › login › should throw UnauthorizedException if wrong email or password is provided

    expect(jest.fn()).not.toBeCalled()

    Expected mock function not to be called but it was called with:
      [{"country_code": "+91", "email": "sayantan.das@codelogicx.com", "first_name": "Sayantan", "id": 1, "image": "image.url", "last_name": "Das", "password": "$2a$10$.5OelkOKIn9rRuXMsge.yO8tgZdqK8i7PX7knJdjVdqgal7vsky16", "phone_number": "8013220938", "registration_status": "verified"}]

      115 | 
      116 |       await expect(userController.login(loginPayload)).rejects.toThrow(UnauthorizedException);
    > 117 |       await expect(authService.generateUserAccessToken).not.toBeCalled();
          |                                                             ^
      118 |     });
      119 |   });
      120 | });

失败是因为成功登录的测试用例调用了generateAccessToken方法。如果删除成功的登录测试用例,它将正常工作。我在这里做错什么了吗?

1 个答案:

答案 0 :(得分:1)

将用于设置模拟并调用beforeAll的{​​{1}}挂钩更改为Test.createTestingModule,以为每个测试用例创建新的模拟,请参见{{3}中的示例}。在大多数情况下,您不会注意到任何性能变化。