javascript - 使用条件语句对函数进行单元测试

标签 javascript unit-testing testing jestjs

我有一个功能可以跟踪谷歌分析的分析。因此,在我的函数中,我需要查看代码是否存在。

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/

相关文章:

java - 如何构建我的 Android Studio 项目以避免在运行集成了单元测试的应用程序时出现编译问题

ios - 在 iOS 上使用 Appium 生成代码覆盖率

javascript - 使用 Lodash 从集合中删除 "column"的最佳方法?

javascript - 当我尝试访问不存在的属性时,为什么 javascript 没有抛出类型错误?

javascript - Ajax 调用后面的代码。达到完成阶段,但不返回成功或触发代码隐藏功能

spring - MockBean stub 无效

ios - 沙盒用户登录 - 地址无效

javascript - 使用 Firebase、React-Native、Redux 进行数据库 .on 调用的约定?

ruby - 我可以模拟 RSpec double 的类名吗?

ruby-on-rails-3 - rails 3 单元测试 - 定义将在每次测试之前运行的通用设置方法