【问题标题】:Jest how to test if a mocked function is called开玩笑如何测试是否调用了模拟函数
【发布时间】:2020-01-02 10:40:27
【问题描述】:

在我的玩笑测试中,我模拟了我这样制作的服务:

jest.mock("../../services/testService");

这很好用。现在我想测试一个模拟函数是否被调用了怎么做?

它试图将模拟放在这样的变量中:

const fn = jest.mock("../../services/testService");

但是当我这样做时,我得到了错误,因为测试现在指的是真正的测试服务,而不是模拟的。

谁能告诉我如何测试一个模拟函数是否被调用?

【问题讨论】:

  • 提供你要测试的代码。
  • @slideshowp2 已将名为 testCall() 的函数放入模拟的 testService 中,现在我想知道是否调用了 testCall。你不需要我已经提供的更多代码。

标签: unit-testing react-native testing mocking jestjs


【解决方案1】:

你可以做类似的事情

//this is the key to know if a function has been called
const yourFunction = jest.fn() 
jest.doMock('../../services/testService', () => ({
  testService: {
    yourFunction
  },
}))

然后使用yourFunction上的断言被调用。

编辑: 我认为如果您尝试模拟 react-native-push-notification,这应该可以工作:

const localNotification = jest.fn() 
jest.doMock('react-native-push-notification', () => ({
  PushNotification: {
    configure: () => {},
    default: () => {},
    localNotification
  },
}))

【讨论】:

  • 嗨@Ian Vasco 我正在尝试模拟react-native-push-notification 模块的Pushnotification。我试过这样: const yourFunction = jest.fn() jest.doMock('react-native-push-notification', () => ({ default: jest.fn(), configure: jest.fn() , localNotification: {yourFunction} }));尝试过的Als没有括号但不起作用我想知道是否调用了LocalNotifcation
  • 如果我使用您的代码,我会收到错误消息:Jest 遇到了意外的令牌 这通常意味着您正在尝试导入 Jest 无法解析的文件,例如它不是纯 JavaScript。默认情况下,如果 Jest 看到 Babel 配置,它将使用它来转换您的文件,忽略“node_modules”。
猜你喜欢
  • 1970-01-01
  • 2020-12-16
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 2018-06-03
  • 2020-12-17
  • 2022-06-10
  • 1970-01-01
相关资源
最近更新 更多