I am using jest to spy window object to define my own window.scrollY value for my nuxt js component.
My jest codes:
const winSpy = jest.spyOn(global, 'window', 'get')
winSpy.mockImplementation(() => ({
scrollY: 200
}))
It works fine, but the error below is shown in terminal:
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')".] {
What is the problem?
Can anyone help me to fix that?
CodePudding user response:
You need to include the original window
properties in the mockImplementation
:
describe('MyComponent', () => {
it('reads scrollY', () => {
const originalWindow = { ...window }
const windowSpy = jest.spyOn(global, 'window', 'get')
windowSpy.mockImplementation(() => ({
...originalWindow,