In my ponent I check whether the page is reloaded and redirect to another page. I do it by following code.
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);
}
}, []);
problem is I keep getting error in my Jest / react-test-library test cases as below
TypeError: window.performance.getEntriesByType is not a function
Even I tried to mock it like below but had no success.
window.performance = {
getEntriesByType: jest.fn().mockReturnValue([{ type: "reload" }]),
measure: jest.fn()
};
Can someone point me to the right direction? thanks in advance.
In my ponent I check whether the page is reloaded and redirect to another page. I do it by following code.
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);
}
}, []);
problem is I keep getting error in my Jest / react-test-library test cases as below
TypeError: window.performance.getEntriesByType is not a function
Even I tried to mock it like below but had no success.
window.performance = {
getEntriesByType: jest.fn().mockReturnValue([{ type: "reload" }]),
measure: jest.fn()
};
Can someone point me to the right direction? thanks in advance.
Share Improve this question asked Jun 3, 2021 at 4:12 Reshan KumarasingamReshan Kumarasingam 4538 silver badges25 bronze badges1 Answer
Reset to default 6window.performance object is read-only property, you can't assign a value to it. Instead, you can use Object.defineProperty() method to define read-only property.
E.g.
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 ponent</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 />);
});
});
test result:
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