如何用玩笑模拟猫鼬链接查询

dul*_*xyz 1 unit-testing mocking method-chaining node.js jestjs

在测试套件上,我想用链接方法模拟模型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();
  }
Run Code Online (Sandbox Code Playgroud)

测试

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);
    });
Run Code Online (Sandbox Code Playgroud)

错误信息

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

mga*_*cia 5

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

UserModel.findOne = jest.fn().mockImplementationOnce(() => ({ select: jest.fn().mockResolvedValueOnce(UserFactory.successResponse)}));
Run Code Online (Sandbox Code Playgroud)