Skip to content Skip to sidebar Skip to footer

When Mutating A Module Object, Why Are Curly Brace Imports Not Changed?

I'm playing around with tidying up a code base that does some direct module mutations, rather than using any mocking behaviour, and I've noticed something odd. If I, starting with

Solution 1:

This is related to When the variables/constants are created.

Import is "executed" before you mutate your object and the constant foo, is then created before you mutate React.foo.

const obj = {a: 1, b: 2};
const a = obj.a; // import
obj.a = 42; // your mock injectionconsole.log(a); // it will keep returning 1    

The way this is handled, is that when a (foo or useContext in your example) is created, it points to the position of memory hold by obj.a, which contains a 1 in the moment of creation. Then obj.a points to a new position of memory where a 42 is stored, but obj.a and a are independent one to another.

In your case my recommendation is to use a Dependency Injection solution.

Either App receive a parameter for which dependency it needs, and then you mock it in the test. <App foo={myFooMock} /> or another usual solution is to sent a context, and have a context creator for Tests with mocks and a context creator for production app.

const myMockedContext = {foo: 'foo', useContext: jest.fn()};
const { getByText } = render(<Appcontext={myMockedContext} />);

Normally you would want to have as much of your real code in your test as possible, all your business logic so that your test fail as soon as there are changes in interfaces or error in type returns or any other unexpected behaviour among your different areas of code.

But this is an ongoing discussion between Mockist and Classists in the TDD community.

HTH

Post a Comment for "When Mutating A Module Object, Why Are Curly Brace Imports Not Changed?"