Jest mock the same function twice with different arguments

后端 未结 2 1598
不思量自难忘°
不思量自难忘° 2021-01-17 07:59

I\'m new to JEST and I\'m currently testing a Javascript component that makes an API call in its onComponentDidMount. Depending on the return data of the ajax call (api call

相关标签:
2条回答
  • 2021-01-17 08:47

    Please check the Jest docs on this. You can return different values when mocking a function and once return a value you wish and then later a different value.

    0 讨论(0)
  • 2021-01-17 08:51

    If you want the mock to return different results on each call:

    Use mockReturnValueOnce

    myMock
      .mockReturnValueOnce(10)
      .mockReturnValueOnce('x')
      .mockReturnValue(true);
    

    will return 10 on the first call, 'x' on the second call and true anytime after that.

    If you want to check the arguments that the mock has been called with:

    Use toHaveBeenNthCalledWith

    expect(mock).toHaveBeenNthCalledWith(1, 'first call args');
    expect(mock).toHaveBeenNthCalledWith(2, 'second call args');
    
    0 讨论(0)
提交回复
热议问题