我有一个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()
})