问题
I have been trying to test an else block for when window is undefined. As I'm using Next.js the window will be undefined during server side rendering (SSR). At present I can not find a way to do this.
Any help is much appreciated.
I have tried setting window = undefined
and global.window = undefined
in the test and within the definition before function (both all and each options). Both approaches have not been successful.
When Googling the closest answer I can find is mocking or spying on a window method but this doesn't answer my problem. I have also found people noting you can run the test as a Node application (thus SSR) but not sure how this can be done for one test.
I have provided an example below of what I am trying to test and how.
Function to Test
export default () => {
console.log(typeof window); // This is always an object and never undefined
const language =
typeof window !== 'undefined'
? window.navigator.userLanguage || window.navigator.language || 'en'
: 'en';
return language;
};
Jest Test
import getLanguage = './getLanguage';
describe('Get Language SSR', () => {
const realWindow = window;
beforeAll(() => {
window = undefined;
});
afterAll(() => {
window = realWindow;
});
it('should return "en"', () => {
expect(getLanguage()).toEqual('en');
})
});
The code coverage shows that the else block is never hit.
回答1:
"By adding a @jest-environment docblock at the top of the file, you can specify another environment to be used for all tests in that file":
/**
* @jest-environment node
*/
import getLanguage from './getLanguage';
describe('Get Language SSR', () => {
it('should return "en"', () => {
expect(getLanguage()).toEqual('en'); // SUCCESS
})
});
The @jest-environment
docblock will set the test environment for this test file to node
causing window
to be undefined
and resulting in the test passing.
来源:https://stackoverflow.com/questions/54038514/how-can-i-set-window-to-undefined-in-order-to-test-the-ssr-rendering-in-an-isomo