gpt4 book ai didi

javascript - 模拟 window.performance.getEntriesByType

转载 作者:行者123 更新时间:2023-12-05 03:41:21 26 4
gpt4 key购买 nike

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

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-test-library 测试用例中不断出现错误,如下所示

TypeError: window.performance.getEntriesByType is not a function

enter image description here

我什至尝试像下面那样模拟它,但没有成功。

window.performance = {
getEntriesByType: jest.fn().mockReturnValue([{ type: "reload" }]),
measure: jest.fn()
};

有人能指出我正确的方向吗?提前致谢。

最佳答案

window.performance对象是只读 属性,您不能为其赋值。相反,您可以使用 Object.defineProperty()定义只读属性的方法。

例如

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>;
}

index.test.jsx:

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

关于javascript - 模拟 window.performance.getEntriesByType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67815262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com