【问题标题】:Jest response mock function not assigning correct response for send and status method开玩笑的响应模拟函数没有为发送和状态方法分配正确的响应
【发布时间】:2021-02-02 22:32:24
【问题描述】:

我正在尝试将单元测试写入具有错误场景的方法,将状态抛出为 404 并在响应中返回未找到该场景的发送方法。我模拟了响应方法并找到了一个方法,验证了 findOne toHaveBeenCalledWith(),它通过了。当检查 toHaveBeenCalledWith() 的发送和状态方法响应失败时。最终出现错误,No of calls:0

Error.ts

  static throwError(errorDef?: string | Error | ErrorMessage, fields = FIELDS): never {
    if ((errorDef as APIError)?.fields) {
      throw errorDef;
    }
    response.status(errorDef.statusCode).send({ message: errorDef.message, fields: {} });

  }

方法.ts

testMethod = async (request: Request, response: Response, entityType: EntityType): Promise<void> => {
    tryCatch(async () => {
      // db validation
      const document = await model.findOne({ email: request.query.email }, false);
      if (!document) {
        throwError({
          name: 'Validation Error',
          message: 'Not Found.',
          statusCode: 404,
        });
      }
}

test.ts


describe('Password Reset', () => {
  // Preparing
  const response: Partial<Response> = {};
  response.status = jest.fn().mockReturnValue(response);
  response.send = jest.fn().mockReturnValue(response);
  // resetSendPasscode Test suite
  describe('testMethod', () => {
    it('should throw error when document not found.', async () => {
      // Preparing
      const request: Partial<Request> = {
        query: {
          email: 'user@gmail.com',
        },
      };
      const spyFindOne = jest.spyOn(userModel.getModel(), 'findOne').mockReturnValueOnce(Promise.resolve(null) as any);
      // Verifying
      await passwordResetController.testMethod(request as Request, response as Response, EntityType.User);
      expect(spyFindOne).toHaveBeenCalledWith({ user_email: 'user@gmail.com' }, false); // this expect block get passed
      expect(response.status).toHaveBeenCalledWith(404); 
      expect(response.send).toHaveBeenCalledWith({ fields: {}, message: 'Not found.' });
      spyFindOne.mockClear();
    });
    });
});

【问题讨论】:

  • throwError()中,throw不应该在末尾,以便在执行停止之前设置响应状态吗?
  • 请不要从您的问题中删除代码,除非您确定您删除的代码不会帮助该问题的读者更好地理解它。

标签: javascript node.js typescript jestjs


【解决方案1】:

我认为如果您将response 作为参数传递给throwError,我认为可以解决此问题(我实际上不确定为什么tsc 在编译时不会抱怨...)。因此,将您的方法签名更改为:

static throwError(response: Response, errorDef?: string | Error | ErrorMessage, fields = FIELDS): void { ... }

并调用它

throwError(response, {
  name: 'Validation Error',
  message: 'Not Found.',
  statusCode: 404,
});

【讨论】:

  • 我忘了添加 error.ts 方法。有一个方法throwError我们发送响应。我已经更新了上面的代码
猜你喜欢
  • 2019-12-19
  • 2021-11-22
  • 1970-01-01
  • 2022-01-04
  • 2022-12-15
  • 2018-10-29
  • 1970-01-01
  • 2021-05-22
  • 2021-02-07
相关资源
最近更新 更多