How to mock an exported const in jest

后端 未结 8 1790
借酒劲吻你
借酒劲吻你 2020-12-23 18:35

I have a file that relies on an exported const variable. This variable is set to true but if ever needed can be set to false manually

8条回答
  •  孤城傲影
    2020-12-23 19:40

    I solved this by initializing constants from ContstantsFile.js in reducers. And placed it in redux store. As jest.mock was not able to mock the contstantsFile.js

    constantsFile.js
    -----------------
    const MY_CONSTANTS = {
    MY_CONSTANT1: "TEST",
    MY_CONSTANT2: "BEST",
    };
    export defualt MY_CONSTANTS;
    
    reducers/index.js
    -----------------
    import MY_CONST from "./constantsFile";
    
    const initialState = {
    ...MY_CONST
    }
    export const AbcReducer = (state = initialState, action) => {.....}
    
    ABC.jsx
    ------------
    import { useSelector } from 'react-redux';
    const ABC = () => {
    const const1 = useSelector(state) => state. AbcReducer. MY_CONSTANT1:
    const const2 = useSelector(state) => state. AbcReducer. MY_CONSTANT2:
    .......
    

    Now we can easily mock the store in test.jsx and provide the values to constant that we want.

    Abc.text.jsx
    -------------
    import thunk from 'redux-thunk';
    import configureMockStore from 'redux-mock-store';
    
    describe('Abc mock constants in jest', () => {
    const mockStore = configureMockStore([thunk]);
    let store = mockStore({
       AbcReducer: {
          MY_CONSTANT1 ="MOCKTEST",
          MY_CONSTANT2 = "MOCKBEST",
       }
    });
    
    test('your test here', () => { .....
    

    Now when the test runs it will always pick the constant value form mock store.

提交回复
热议问题