0

I'd like to test a react component, which displays a list of element or not, based on the return value of a custom hook.

In my first test, I want to make sure nothing is displayed, so I used this at the top of my test method:

jest.mock('components/section/hooks/use-sections-overview', () => {
  return {
    useSectionsOverview: () => ({
      sections: [],
    }),
  };
});

in the second test, I want to display something, so I used this one

jest.mock('components/section/hooks/use-sections-overview', () => {
  return {
    useSectionsOverview: () => ({
      sections: [
         {id: '1', content: 'test'}
      ],
    }),
  };
});

Unfortunately, when running my test, it always returns an empty array.

I tried adding jest.restoreAllmocks(); in my afterEach method, but this doesn't change anything.

Am I missing something ?

0

1 Answer 1

1

jest.mock will always be pulled to the top of the file and executed first, so your tests can't change the mock beyond the initial one.

What you can do though is have the mock point at some kind of stubbed response, wrapped inside a jest.fn call (to defer execution), so it's evaluated after each change.

e.g.

const sections_stub = {
    sections: [],
};

jest.mock('components/section/hooks/use-sections-overview', () => ({
    useSectionsOverview: jest.fn(() => sections_stub),
}));

describe('my component', () => {
    it('test 1', () => {
         sections_stub.sections = [];

          // run your test
    });
    it('test 2', () => {
         sections_stub.sections = [
            { id: '1', content: 'test'}
         ];

          // run your other test
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.