javascript - Jest : How to test for something inside of a callback function?

标签 javascript reactjs jestjs

在我的 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()
})

最佳答案

最简单的方法是显式声明你的回调

const callback = (error, decoded) => {
    if (error) {
        console.error(error)
    } else {
        redirect(context, '/')
    }
}

并单独测试。

另一个选择是为 jwt.verify 做一个更智能的模拟

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

这样你的实际回调将被调用并可以被测试

关于javascript - Jest : How to test for something inside of a callback function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50790779/

相关文章:

node.js - 使用 POST 请求将数据从 Node 服务器发送回 React 客户端

jestjs - 使用 vue-test-utils 和 JEST 模拟 $root

node.js - 如何将 Harmony_async_iteration 与 jest 结合使用?

使用 Jest 模块注入(inject)的 Angularjs 测试

javascript - 为什么在javascript对象的参数元素中反斜杠?

javascript - 从 nodejs 以 html 格式共享文件

用于删除不需要的 <br> 的 Javascript 正则表达式,

javascript - Facebook 应用程序 SSL 更改 - AJAX Flash/服务器数据安全

javascript - 在 React JS 中获取多数组中的 JSON 数据时出错?

javascript - 通过 React 组件传递数组