我有一个功能可以跟踪谷歌分析的分析。因此,在我的函数中,我需要查看代码是否存在。
Analytics.js
const gaCode = process.env.REACT_APP_GA_TRACKING_CODE;
const gaCodeExists = gaCode && gaCode.Length > 0;
function trackEvent(category = "Event", name) {
if(gaCodeExists) {
GoogleAnalytics.event({
category,
action: name,
});
}
return;
}
export default {
gaCodeExists,
trackEvent
}
起初我是这样做的(我很确定我做得不对)。
describe('Testing analytics', () => {
beforeEach(() => {
Analytics.trackEvent(null, 'Tracking');
});
it('should not call google analytics', () => {
if (!gaCodeExists) {
const mockGoogleAnalytics = jest.fn(() => GoogleAnalytics.event);
expect(mockGoogleAnalytics.mock.calls.length).toBe(0);
}
});
})
阅读一些博客文章并查看 stackover flow questions 后。我将其更改为这样,我认为我正在 mock gaCodeExists 变量,如下所示。
import constants from '../index';
import { isUsingGoogleAnalytics } from '../index';
describe('Analytics Testing', () => {
it('Should test trackEvent', () => {
constants.isUsingGoogleAnalytics = true;
expect(constants.isUsingGoogleAnalytics).toBe(true);
});
});
现在我陷入困境,如何对 trackEvent
函数进行测试。如何将模拟 gaCodeExists 变量应用于它?测试用例是,如果 gaCodeExists 为 true,则 expect(mockFunction).toHaveBeenCalled(1)
。
P.S:我是测试新手。
最佳答案
const gaCode = process.env.REACT_APP_GA_TRACKING_CODE;
const gaCodeExists = gaCode && gaCode.Length > 0;
function trackEvent(category = "Event", name, gaCodeExists) {
if(gaCodeExists) {
GoogleAnalytics.event({
category,
action: name,
})
}
}
export default {
gaCodeExists,
trackEvent
}
首先像这样更改您的 Analytics 代码,您的测试文件应如下所示
import { UsingGoogleAnalytics } from '../index' // i don't know what this file is
import { gaCodeExistsis, trackEvent } from './Analytics'
describe('Analytics Testing', () => {
beforeEach(() => {
expect(gaCodeExists).toHaveBeenCalledWith(true)
expect(trackEvent).toEqual(jasmine.any(Function))
})
it('track event was called without params', () => {
expect(trackEvent()).toBe(1); // replace 1 with desire output without params
})
it('track event was called with params', () => {
expect(trackEvent("somecategory", "somename", gaCodeExistsis)).toBe(1); // replace 1 with desire output with params
})
});
关于javascript - 使用条件语句对函数进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111571/