【问题标题】:How to assert the properties of a class inside a mock function with jest如何用玩笑在模拟函数中断言类的属性
【发布时间】:2020-03-20 23:49:16
【问题描述】:

我遇到了将类作为参数传递的模拟函数的问题。由于某种原因,它似乎没有正确断言内容

// ErrorHandler.js
class ErrorHandler extends Error {
  constructor(status, reason) {
    super();
    this.status = status;
    this.reason = reason;
  }
}

export {
  ErrorHandler
}

// express file express.js
const method = async (req, res, next) => {
  try {
    throw new ErrorHandler(401, 'error')
    next()
  } catch (error) {
    next(error)
  }
}

// test file
it('should call the next method with the proper error', async () => {
 const request = {
   body: {}
 }
 const next = jest.fn()
 const response = mockResponse() // here it's just a simple mock
 await method(request, response, next)

 expect(next).toHaveBeenCalledWith(
  // here the problem is that it doesn't seem to assert the parameters
  // and this test is passing
  new ErrorHandler('random text')
 )
})

我尝试模拟 ErrorHandler 类,但是它给出了另一个错误,它无法再比较下一个方法

【问题讨论】:

  • postLogin和method一样吗? toHaveBeenCalledTimes 也需要一个数字。请给一个正确的minimal reproducible example。
  • @jonrsharpe 是的,确实是一样的,我也把它改成了“With”

标签: node.js express jestjs


【解决方案1】:

问题在于 Jest 试图比较两个错误对象,但并不真正知道如何进行比较。您可以通过一个简单的断言来看到这一点:

expect(new ErrorHandler(404, 'not found')).not.toEqual(new ErrorHandler(401, 'unauthorized'))

结果:

expect(received).not.toEqual(expected) // deep equality

Expected: not [Error]

你需要更具体,例如:

expect(next).toHaveBeenCalled();
const [err] = next.mock.calls[0];
expect(err).toMatchObject({ status: 401, reason: 'error' });

【讨论】:

  • 感谢您的回答,确实无法仅凭一个断言进行该测试。在我使用的下一个函数的情况下://example expect(next).toHaveBeenCalledWith(new ErrorHandler)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-08
  • 2018-02-14
  • 2018-05-22
  • 1970-01-01
  • 2023-02-15
  • 2019-10-01
  • 1970-01-01
相关资源
最近更新 更多