Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Mock window.performance.getEntriesByType_Javascript_Reactjs_Unit Testing_Mocking_React Testing Library - Fatal编程技术网

Javascript Mock window.performance.getEntriesByType

Javascript Mock window.performance.getEntriesByType,javascript,reactjs,unit-testing,mocking,react-testing-library,Javascript,Reactjs,Unit Testing,Mocking,React Testing Library,在我的组件中,我检查页面是否被重新加载并重定向到另一个页面。我通过下面的代码来实现 useEffect(() => { //this will prevent users from accidently refreshing / closing tab window.onbeforeunload = () => { return ""; }; //check whether user reloaded if (

在我的组件中,我检查页面是否被重新加载并重定向到另一个页面。我通过下面的代码来实现

useEffect(() => {
    //this will prevent users from accidently refreshing / closing tab
    window.onbeforeunload = () => {
      return "";
    };
   //check whether user reloaded
    if (
      window.performance.getEntriesByType("navigation")[0].type === "reload"
    ) {
      openExternalURL(process.env.GATSBY_MARKETING_URL);
    }
  }, []);
问题是我的Jest/react测试库测试用例中不断出现错误,如下所示

TypeError: window.performance.getEntriesByType is not a function

甚至我也试着像下面那样嘲笑它,但没有成功

window.performance = {
  getEntriesByType: jest.fn().mockReturnValue([{ type: "reload" }]),
  measure: jest.fn()
};
有人能给我指一下正确的方向吗?提前感谢。

对象是只读属性,您无法为其赋值。相反,您可以使用方法定义只读属性

例如

index.jsx

import React, { useEffect } from 'react';

export function MyComponent() {
  useEffect(() => {
    window.onbeforeunload = () => {
      return '';
    };
    if (window.performance.getEntriesByType('navigation')[0].type === 'reload') {
      console.log('open external url');
    }
  }, []);

  return <div>my component</div>;
}
import React from 'react';
import { render } from '@testing-library/react';
import { MyComponent } from './';

describe('67815262', () => {
  it('should pass', () => {
    Object.defineProperty(window, 'performance', {
      value: {
        getEntriesByType: jest.fn().mockReturnValue([{ type: 'reload' }]),
        measure: jest.fn(),
      },
    });

    render(<MyComponent />);
  });
});
测试结果:

 PASS  examples/67815262/index.test.jsx (8.673 s)
  67815262
    ✓ should pass (38 ms)

  console.log
    open external url

      at examples/67815262/index.jsx:9:15

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.295 s