当我试图监视 window 对象时出现 UnhandledPromiseRejection (jest + nuxt js)
UnhandledPromiseRejection when I am trying to spy window object (jest + nuxt js)
我正在使用 jest 来监视 window 对象来为我的 nuxt js 组件定义我自己的 window.scrollY 值。
我的笑话代码:
const winSpy = jest.spyOn(global, 'window', 'get')
winSpy.mockImplementation(() => ({
scrollY: 200
}))
它工作正常,但在终端中显示以下错误:
node:internal/process/promises:265
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: This error originated either by throwing inside of an
async function without a catch block, or by rejecting a promise which was not handled
with .catch(). The promise rejected with the reason "TypeError: Cannot read
properties of undefined (reading 'get')".] {
问题是什么?
谁能帮我解决这个问题?
您需要在 mockImplementation
中包含原始 window
属性:
describe('MyComponent', () => {
it('reads scrollY', () => {
const originalWindow = { ...window }
const windowSpy = jest.spyOn(global, 'window', 'get')
windowSpy.mockImplementation(() => ({
...originalWindow,
scrollY: 200,
}))
const wrapper = shallowMount(MyComponent)
expect(wrapper.vm.top).toBe(200)
})
})
我正在使用 jest 来监视 window 对象来为我的 nuxt js 组件定义我自己的 window.scrollY 值。
我的笑话代码:
const winSpy = jest.spyOn(global, 'window', 'get')
winSpy.mockImplementation(() => ({
scrollY: 200
}))
它工作正常,但在终端中显示以下错误:
node:internal/process/promises:265
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: This error originated either by throwing inside of an
async function without a catch block, or by rejecting a promise which was not handled
with .catch(). The promise rejected with the reason "TypeError: Cannot read
properties of undefined (reading 'get')".] {
问题是什么?
谁能帮我解决这个问题?
您需要在 mockImplementation
中包含原始 window
属性:
describe('MyComponent', () => {
it('reads scrollY', () => {
const originalWindow = { ...window }
const windowSpy = jest.spyOn(global, 'window', 'get')
windowSpy.mockImplementation(() => ({
...originalWindow,
scrollY: 200,
}))
const wrapper = shallowMount(MyComponent)
expect(wrapper.vm.top).toBe(200)
})
})