开玩笑用相同的参数两次模拟相同的函数 [英] Jest mock the same function twice with different arguments

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

问题描述

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

推荐答案

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

使用 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.

#如果要检查已使用该模拟调用的参数:

使用 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')

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

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