Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

javascript - Jest mock the same function twice with different arguments

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) my component either display a table or a simple text.

My JEST test are fairly simple, for now I'm only testing to match the current snapshots. So since my api call can return different data, my snapshot can be of two different aspects : 1) one with a table 2) one with a simple text.

I successfully mocked the service like that

jest.mock("/myService", () => ({
  index: (data, callback) => {
    const return = [
      {
        {...}
      },
    ]
    callback(return)
  },
}))

My component does the myService.index() call correctly, all I wish to pass to it different values which its gonna use to make the callback.

Here's how the it looks like

it("has proper snapshot", () => {
    const props = {...}
    const component = shallow(<MyComponent {...props} />)
    expect(component).toMatchSnapshot()
  })

This works great for the first exemple but I cannot seem to find a correct answer that suits me. Can you help me ? :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1- 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.

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

Use toHaveBeenNthCalledWith

expect(mock).toHaveBeenNthCalledWith(1, '1st call args');
expect(mock).toHaveBeenNthCalledWith(2, '2nd call arg 1', '2nd call arg 2');

will assert that

  • the mock was called with '1st call args' the first time it was called -> mock('1st call args')

  • the mock was called with '2nd call arg 1' and '2nd call arg 2' the second time it was called -> mock('2nd call arg 1', '2nd call arg 2')

3- If you want a specific response based on the function parameter

It is not supported by jest by default but you can have a look at jest-when which allows you to do something like:

when(fn).calledWith(1).mockReturnValue('yay!')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...