我的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()
})发布于 2018-06-11 16:39:33
最简单的方法是显式声明您的回调
const callback = (error, decoded) => {
if (error) {
console.error(error)
} else {
redirect(context, '/')
}
}然后单独测试它。
另一种选择是为jwt.verify制作一个更智能的模拟
jwt.verify = jest.fn((token, secret, callback) => callback())这样,您的实际回调将被调用并可以进行测试
https://stackoverflow.com/questions/50790779
复制相似问题