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
Two important concepts from Exploring ES6 (which are also applicable to TypeScript Modules ):
In ES6, imports are live read-only views on exported values
and
while you can't change the values of imports, you can change the objects that they are referring to.
app-config
exports config
which is an object .
config
can't be assigned to something else, but the object it refers to can be changed .
Any code that imports config
gets a live view of the object and will automatically see any modifications to the object:
import { config } from './app-config';
...
it(testTitle, () => {
config.key = mockStatusOfConfigKey; // modify the config object
expect(isSomethingWhatINeedSelector(state)).toBe(expected); // SUCCESS
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.