简体   繁体   English

Mocking 只有一个带有 Jest 的“窗口”属性

[英]Mocking only a single `window` property with Jest

I have a React component that makes a call to window.location.href .我有一个调用window.location.href的 React 组件。

As part of my Jest test, I mock the value of window.location.href as follows:作为我 Jest 测试的一部分,我模拟了window.location.href的值,如下所示:

const mockWindow = { location: { href: 'https://stackoverflow.com/questions' } };
jest.spyOn(window, 'window', 'get').mockImplementation(() => mockWindow);

const wrapper = mount(<MyComponent />);

However when I run it, I get the following error:但是,当我运行它时,我收到以下错误:

TypeError: Right-hand side of 'instanceof' is not an object

    > |   const wrapper = mount(<MyComponent />);
      |                   ^

This tells me there is an internal React issue when rendering/mounting the component.这告诉我在渲染/安装组件时存在内部 React 问题。 The issue is specifically caused by me mocking the window object.该问题专门由我 mocking window object 引起。 When I uncomment that line and re-run it, it doesn't not raise this error.当我取消注释该行并重新运行它时,它不会引发此错误。

I'm guessing that React internally makes other calls to window.* and because I mocked the whole object, those calls made by React return undefined and the component does not render.React 在内部对window.*进行了其他调用,并且因为我模拟了整个 object,所以 React 进行的那些调用返回undefined并且组件不会呈现。

How do I mock only a single property of window while leaving other properties untouched?如何只模拟window的单个属性,同时保持其他属性不变?

Alternately, are there any other reasons this would error?或者,还有其他原因会出错吗? Or are there other clever ways to get around this issue?还是有其他巧妙的方法来解决这个问题?

Instead of doing jest.spyOn(window, 'window'...) try using (global, 'window'...) like the following:而不是 jest.spyOn(window, 'window'...) 尝试使用 (global, 'window'...) ,如下所示:

const originalWindow = { ...window };
const windowSpy = jest.spyOn(global, "window", "get");
windowSpy.mockImplementation(() => ({
  ...originalWindow,
  location: {
    ...originalWindow.location,
    href: "http://my.test/page",
    replace: mockedReplace,
  },
}));

And after remeber to clean it up:在记住清理它之后:

windowSpy.mockRestore();

You can check out better following this example您可以按照此示例更好地检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM