我正在使用jest测试模块,该模块调用一个函数,该函数又从react-native-google-analytics-bridge调用GoogleAnalyticsTracker。我已经尝试了所有我能想到的(文档有点稀疏)来模拟这个函数,但我总是得到真正的模块而不是模拟模块。你能看出我错误或遗失的那一步吗?
Expected value to be (using ===):
undefined
Received:
{"allowIDFA": [Function allowIDFA], "setAnonymizeIp": [Function setAnonymizeIp], "setAppName": [Function setAppName], "setAppVersion": [Function setAppVersion], "setSamplingRate": [Function setSamplingRate], "setTrackUncaughtExceptions": [Function setTrackUncaughtExceptions], "setUser": [Function setUser], "trackEvent": [Function trackEvent], "trackEventWithCustomDimensionValues": [Function trackEventWithCustomDimensionValues], "trackException": [Function trackException], "trackMultiProductsPurchaseEvent": [Function trackMultiProductsPurchaseEvent], "trackMultiProductsPurchaseEventWithCustomDimensionValues": [Function trackMultiProductsPurchaseEventWithCustomDimensionValues], "trackPurchaseEvent": [Function trackPurchaseEvent], "trackScreenView": [Function trackScreenView], "trackScreenViewWithCustomDimensionValues": [Function trackScreenViewWithCustomDimensionValues], "trackSocialInteraction": [Function trackSocialInteraction], "trackTiming": [Function trackTiming], "transformCustomDimensionsFieldsToIndexes": [Function transformCustomDimensionsFieldsToIndexes]}
...但它始终设法找到未模拟的模块......
{{1}}
答案 0 :(得分:3)
晚了一点,在2019年10月31日之后将不再支持移动版Google Analytics(分析),但这也是一种解决方案(使用Jest module mocks solution)
创建一个包含以下内容的__mocks__/react-native-google-analytics-bridge.js
文件:
export const setAppVersion = jest.fn();
export const setUser = jest.fn();
export const trackScreenView = jest.fn();
export const trackEvent = jest.fn();
export const GoogleAnalyticsTracker = jest.fn().mockImplementation(() => {
return {
setAppVersion,
setUser,
trackScreenView,
trackEvent
};
});
可以随意添加所需的方法,这只是一个子集。仅此一项就可以使依赖于react-native-google-analytics-bridge的测试不会失败。
如果要测试通话,请在测试文件上:
import { setAppVersion } from 'react-native-google-analytics-bridge';
...
expect(setAppVersion).toHaveBeenCalledWith('1.0.0');
答案 1 :(得分:2)
这是答案......你真的需要在尝试模拟之前从模块中获取真实对象!
import {GoogleAnalyticsTracker} from 'react-native-google-analytics-bridge';
jest.mock('react-native-google-analytics-bridge');
我现在可以创建一个跟踪器......
let tracker1 = new GoogleAnalyticsTracker('ABC-123');
...并将其传递给我试图测试的函数。
Jest创建tracker1.trackTiming
,我可以通过使用...
console.log('tracker1',tracker1.trackTiming.mock.calls);
在我的情况下,返回将写入GoogleAnalytics的参数,而不会使用测试数据实际污染我的分析数据。
答案 2 :(得分:1)
您是否尝试将模拟版本用作导入版本?
var GoogleAnalyticsTracker = jest.mock('react-native-google-analytics-bridge');
答案 3 :(得分:1)
您可以使用Jest的genMockFromModule
方法并将其添加到模拟中。
const mockAnalytics = jest.genMockFromModule('react-native-google-analytics-bridge');
module.exports = mockAnalytics;