【问题标题】:How to mock mongoose chaining query with jest如何用玩笑模拟猫鼬链接查询
【发布时间】:2019-05-22 04:34:37
【问题描述】:

在测试套件上,我想使用链接方法 findOne 然后 select 模拟模型

登录服务

public loggingIn = async (loginDTO: LoginDTO) => {
    const user = await UserModel.findOne({ email : loginDTO.email }).select(['_id', 'username', 'email', 'password']);
    if (user) {
      const isPasswordMatching = await bcrypt.compare(loginDTO.password, user.password);
      if (isPasswordMatching) {
        const token = this.generateToken(user);
        const tokenDTO : TokenDTO = {
          access_token: token,
          expiresIn: loginConstant.EXPIRES_IN,
        };
        return tokenDTO;
      }
      throw new InvalidCrendentialsException();
    }
    throw new InvalidCrendentialsException();
  }

测试

it('should return access_token when login is success', async () => {
      UserModel.findOne = jest.fn().mockResolvedValueOnce(UserFactory.successResponse);
      bcrypt.compare = jest.fn().mockResolvedValueOnce(true);
      const loginController = new LoginController();
      const app = new App([loginController]);

      const result = await request(app.getServer())
          .post(`${loginController.path}`)
          .send(loginFactory.validRequest);

      // expect(result.status).toBe(200);
      expect(result.body).toBe(200);
    });

错误消息

user_model_1.default.findOne(...).select 不是函数

【问题讨论】:

    标签: node.js unit-testing mocking jestjs method-chaining


    【解决方案1】:

    为此,您需要定义模拟,以便findOne 方法使用select 方法返回一个对象。一个简单的方法是将你的模拟定义为:

    UserModel.findOne = jest.fn().mockImplementationOnce(() => ({ select: jest.fn().mockResolvedValueOnce(UserFactory.successResponse)}));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 2020-02-08
      • 1970-01-01
      • 2022-10-06
      • 2017-07-25
      • 2019-04-08
      • 2018-06-11
      相关资源
      最近更新 更多