anyone know how I can mock window object for testing the value of feature
? Following is my concept code, I want to test if expEnabled is enable feature is 'exp is enabled'
otherwise feature is 'exp is disable'
I have tried to mocking global.window in jest
and Mocking globals in Jest but it does not seem work for me.
Updated:
after moving the code const expEnabled = typeof window !== 'undefined' && !!window?.app?.initialAppProps?.exp?.my_feature;
into function it seems like use Object.defineProperty
works.
//source code
import Koa from 'koa';
export interface InitialAppProps {
exp: Koa.DefaultState['exp'];
}
const expEnabled = typeof window !== 'undefined' && !!window?.app?.initialAppProps?.exp?.my_feature;
export function testMock(){
return typeof window !== 'undefined' && !!window?.app?.initialAppProps?.exp?.my_feature;
}
//app is Functional component of my app from react
export const feature = [expEnabled ? 'exp is enabled' : 'exp is disable']
export const featureNew = [testMock() ? 'exp is enabled' : 'exp is disable']
//test code
describe('expEnabled', () => {
it('feature should be enabled if expEnabled is trued', () => {
/*
how can I mock expEnabled is true?
I have tried this and console.log before expect. the right value print out but I still fail on expect
Object.defineProperty(global, 'window', {
value: {
app: {initialAppProps: {exp: {my_feature: true}}},
},
writable: true,
});
*/
expect(feature).toEqual('exp is enabled');
});
it('feature should be enabled if expEnabled is trued', () => {
Object.defineProperty(global, 'window', {
value: {
app: {initialAppProps: {exp: {my_feature: true}}},
},
writable: true,
});
expect(featureNew).toEqual('exp is enabled');
})
});