Wednesday, 30 January 2019

How to mock varible that imported in tested module, and it is not a function parameter (do this with describe.each and on each test change mock value)

I need to test function in my ts-module.

module-to-test.ts

import { config } from './app-config';

export const isSomethingWhatINeedSelector = createSelector(
    firstDependencySelector,
    secondDependencySelector,
    (first, second) => config.key && (first || !second)
);

But I don't want to write many test for this case, and I want to try to use describe.each([[],[],[]]) functionality to reduce number of code lines.

And I need to change config.key on each iteration of describe.each. When I do at the beginning of the test-file something like this:

jest.mock('./app-config', () => ({
    config: {
        key : false,
    },
}));

it works for the whole file and all the tests. I want to make mock inside "test/it" functions to change value of key dynamically.

Now I have that code, that doesn't work as expected

describe.each([
    [
        'should be ....',
        true, false
    ],
    [
        'should be ....',
        false, true
    ],
    /* and etc. ... [], [], [] ... only for questnion here is two params*/
])('Functionality of ...', (
    testTitle = '',
    mockStatusOfConfigKey,
    expected,
) => {
    const state = ... /* initial */

    beforeEach(() => {
        jest.resetModules();
        /*....configuring the state*/
    }); 

    it(testTitle, () => {
        jest.mock('./app-config', () => ({ /*...or doMock(), that don't works*/
           config: {
              key : mockStatusOfConfigKey,
           },
        }));
        expect(isSomethingWhatINeedSelector(state)).toBe(expected);
    });
    });

Any ideas how to make mocks dynamically changable inside test functions? config.key is just true/false



from How to mock varible that imported in tested module, and it is not a function parameter (do this with describe.each and on each test change mock value)

No comments:

Post a Comment