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.