最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to mock globals window object in jest in typescript - Stack Overflow

programmeradmin1浏览0评论

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 ponent 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');
  })
});

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 ponent 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');
  })
});
Share Improve this question edited Apr 12, 2021 at 2:17 jacobcan118 asked Apr 11, 2021 at 3:26 jacobcan118jacobcan118 9,17916 gold badges60 silver badges120 bronze badges 1
  • Does this answer your question? How can I mock the JavaScript 'window' object using Jest? – Michael Freidgeim Commented Feb 20, 2023 at 4:22
Add a ment  | 

1 Answer 1

Reset to default 2

Just assign a value to window.app.initialAppProps.exp.my_feature. You need to reset the module before executing each test case since the ./index module will be cached in the require.cache object. This means the value of expEnabled variable will be cached too.

E.g.

index.ts:

declare global {
  interface Window {
    app: {
      initialAppProps: {
        exp: {
          my_feature: boolean;
        };
      };
    };
  }
}

const expEnabled = typeof window !== 'undefined' && !!window.app.initialAppProps.exp.my_feature;
export const feature = [expEnabled ? 'exp is enabled' : 'exp is disable'];

index.test.ts:

describe('67041178', () => {
  beforeAll(() => {
    window.app = {
      initialAppProps: {
        exp: { my_feature: false },
      },
    };
  });
  beforeEach(() => {
    jest.resetModules();
  });
  it('should enable', () => {
    window.app.initialAppProps.exp.my_feature = true;
    const { feature } = require('./');
    expect(feature).toEqual(['exp is enabled']);
  });

  it('should disable', () => {
    window.app.initialAppProps.exp.my_feature = false;
    const { feature } = require('./');
    expect(feature).toEqual(['exp is disable']);
  });
  it('should pass', () => {
    Object.defineProperty(global, 'window', {
      value: {
        app: { initialAppProps: { exp: { my_feature: true } } },
      },
      writable: true,
    });
    const { feature } = require('./');
    expect(feature).toEqual(['exp is enabled']);
  });
});

unit test result:

 PASS  examples/67041178/index.test.ts (13.133 s)
  67041178
    ✓ should enable (8 ms)
    ✓ should disable (1 ms)
    ✓ should pass (1 ms)

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        14.167 s

source code: https://github./mrdulin/jest-v26-codelab/tree/main/examples/67041178

发布评论

评论列表(0)

  1. 暂无评论