Jest 用不同的参数模拟同一个函数两次 [英] Jest mock the same function twice with different arguments

查看:21
本文介绍了Jest 用不同的参数模拟同一个函数两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 JEST 的新手,我目前正在测试一个 Javascript 组件,该组件在其 onComponentDidMount 中进行 API 调用.根据 ajax 调用(api 调用)的返回数据,我的组件要么显示表格,要么显示简单的文本.

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.

我的 JEST 测试相当简单,目前我只是测试以匹配当前的快照.因此,由于我的 api 调用可以返回不同的数据,因此我的快照可以有两个不同的方面:1) 一个带有表格 2) 一个带有简单的文本.

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)
  },
}))

我的组件正确地执行了 myService.index() 调用,我希望向它传递不同的值,这些值将用于进行回调.

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.

这是它的样子

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 ? :)

推荐答案

1- 如果您希望模拟在每次调用时返回不同的结果:

使用 mockReturnValueOnce

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

将在第一次调用时返回 10,在第二次调用时返回 'x',之后的任何时候返回 true.

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

2- 如果您想检查已调用模拟的参数:

使用 toHaveBeenNthCalledWith

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

会断言

  • mock 在第一次被调用时用 '1st call args' 调用 ->mock('1st call args')

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

mock 第二次调用 '2nd call arg 1''2nd call arg 2'称为 ->mock('2nd call arg 1', '2nd call arg 2')

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- 如果您想要基于函数参数的特定响应

jest 默认不支持它,但您可以查看 jest-when这允许您执行以下操作:

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!')

这篇关于Jest 用不同的参数模拟同一个函数两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆