我在@ vue / test-utils和JEST下模拟window.location.replace函数时遇到问题。我很确定我正确地嘲笑了函数,但是JEST没有看到调用。这是我要测试的代码片段:
// function called by response interceptor
const redirectToLogin = async () => {
try {
VueCookie.delete('jwt')
const url = localStorage.getItem('base-url') || window.location.origin
window.location.replace(url + '/jwt/token');
console.log(window.location.replace) //it prints [Function: mockConstructor]
} catch (e) {
console.log(e)
}
}
这也是我测试的一部分:
const location = {
origin: 'http://origin',
replace: jest.fn()
}
delete global.window.location
delete global.window.localStorage
global.window = Object.create(window)
global.window.location = location
global.window.localStorage = {
getItem: jest.fn(),
setItem: jest.fn()
}
api.interceptors.response.handlers.rejected[0]({ response: { data: { error: 'unauthorized', base_url: 'http://base' } } }) // calling interceptor
expect(location.replace).toHaveBeenCalledWith('someurl')
我明白了
预期的模拟函数已被调用: [“ someurl”] 但是它没有被调用。