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

标签 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方法。如果我删除成功的登录测试用例,它就可以正常工作。我在这里做错了什么吗?

最佳答案

beforeAll 钩子(Hook)(在其中设置模拟并调用 Test.createTestingModule)更改为 beforeEach 以便为每个测试创建新的模拟案例,请参阅 test docs 中的示例。在大多数情况下,您不会注意到任何性能变化。

关于node.js - Expect(spiedMethod).not.toBeCalled() 失败,因为它正在被另一个测试调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54704921/

相关文章:

node.js - Passport.js session 困惑

java - 模拟静态 Liferay 方法

javascript - 更新未包含在 act(...) 中并且模拟函数未触发。 react 测试库,开 Jest

javascript - 在 Jest 和 Enzyme 测试中触发 useEffect

reactjs - 在 componentDidMount 中获取时如何测试 react 组件?

node.js - nodejs/npm/webpack : adding dependency as "file:/some/path" doesn't work

node.js - 范围在快速路线内工作有点奇怪

node.js - NodeJS/Express 无法连接到在 docker 中运行的 mongodb

c# - 对一些输入进行各种单元测试

reactjs - jest 中的模拟动画完成回调