Jest:如何测试回调函数内的内容?

3

我有一个React组件中的静态函数,我想使用Jest进行测试。

static async getInitialProps (context, apolloClient) {
  const { req } = context
  const initProps = { user: {} }

  if (req && req.headers) {
    const cookies = req.headers.cookie
    if (typeof cookies === 'string') {
      const cookiesJSON = jsHttpCookie.parse(cookies)
      initProps.token = cookiesJSON['auth-token']
      if (cookiesJSON['auth-token']) {
        jwt.verify(cookiesJSON['auth-token'], secret, (error, decoded) => {
          if (error) {
            console.error(error)
          } else {
            redirect(context, '/')
          }
        })
      }
    }
  }
}

这是我目前得到的代码,用于测试jwt.verify的调用。但是,我要如何测试它的回调函数呢?如果没有错误,我想检查redirect的调用。
test('should call redirect', () => {
  // SETUP
  const context = { req: { headers: { cookie: 'string' } } }
  jsHttpCookie.parse = jest.fn().mockReturnValueOnce({ 'auth-token': 'token' })
  jwt.verify = jest.fn(() => redirect)
  // EXECUTE
  Page.getInitialProps(context, {})
  // VERIFY
  expect(jwt.verify).toHaveBeenCalled()
})
1个回答

3
最简单的方法是明确声明您的回调函数。
const callback = (error, decoded) => {
    if (error) {
        console.error(error)
    } else {
        redirect(context, '/')
    }
}

还有一个选择是为jwt.verify创建一个更智能的模拟。

并单独测试它。

jwt.verify = jest.fn((token, secret, callback) => callback())

这样做可以调用实际的回调函数并进行测试。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接