开玩笑如何测试一个模拟函数是否被调用

时间:2020-01-02 10:40:27

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

在开玩笑的测试中,我模拟了我这样做的一项服务:

$prestations = Prestation::whereHas('service', function($subQuery) use($search) {
                $subQuery->where('name', 'like', '%' . $search . '%');
            })->with(
    [
        'service' => function($service) use($search){
            $service->select(['id','name'])->where('name', 'like', '%' . $search . '%');
        },
    ]
)->orderBy($orderBy, $orderDirection)->simplePaginate(50);

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

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

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

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

有人可以告诉我如何测试是否调用了模拟功能吗?

1 个答案:

答案 0 :(得分:0)

您可以做类似的事情

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