1

I have a function that I have mocked in my test cases file.

MyService.getConfigsForEntity = jest.fn().mockReturnValue(
    new Promise(resolve => {
        let response = [];
        resolve(response);
    })
);

Now I want all my test cases in that file to use this mock like

describe('Should render Component Page', () => {
    it('should call the API', async () => {
        const {container} = render(<MyComp entityName='entity1'/>);
        await wait(() => expect(MyService.getConfigsForEntity).toHaveBeenCalled());
    });
});

The only issue is in only one of the test case I want to mock the return value differently.

But all other test cases before and after can use the global mock.

describe('Should call API on link click', () => {
    it('should call the API on link click', async () => {
       const spy = jest.spyOn(MyService, 'getConfigsForEntity ').mockReturnValue(
           new Promise(resolve => {
           let response = [{
               "itemName": "Dummy"
           }];
           resolve(response);
        });
        const {container} = render(<MyComp entityName='entity1'/>);
        await wait(() => expect(spy).toHaveBeenCalled());
        spy.mockClear();
    });
});

The problem is , once I mock the function differently inside one test case , all other test cases after that test case, that are using the global mock , are failing,

But it only works if I put the test case after all other test cases.

What am I doing wrong?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
StrugglingCoder
  • 4,781
  • 16
  • 69
  • 103

2 Answers2

7

You can try with mockRestore():

beforeEach(() => {
  spy.mockRestore();
});
Hieu Dang
  • 343
  • 3
  • 11
1

have you tried?

  beforeEach(() => {
     jest.clearAllMocks();
  })
Red Baron
  • 7,181
  • 10
  • 39
  • 86