gpt4 book ai didi

unit-testing - ReferenceError : ga is not defined [Ionic 2. 2 使用 Karma 进行单元测试]

转载 作者:行者123 更新时间:2023-12-03 15:56:19 25 4
gpt4 key购买 nike

我正在向我管理的 Ionic 2.2.0 应用程序添加单元测试,但我的组件在遇到 Google Analytics 代码时在测试时崩溃。我正在使用 Ionic's official unit testing example作为基础,和my current progress can be seen on our public repo .

我的项目使用 Google Analytics,它被添加到 HTML 并在运行时下载(因为我们有不同的开发 key 和生产 key )。

初始化 Analytics 的代码在我的 main.ts 中,它设置了一个全局变量 ga,该变量随后在整个应用程序中可用。

我开始测试应用程序的第一页,它使用 Analytics。当我运行测试时,遇到以下错误

Component should be created FAILED

ReferenceError: ga is not defined

at new MyBusesComponent (webpack:///src/pages/my-buses/my-buses.component.ts:33:6 <- karma-test-shim.js:138419:9)

at new Wrapper_MyBusesComponent (/DynamicTestModule/MyBusesComponent/wrapper.ngfactory.js:7:18)

at CompiledTemplate.proxyViewClass.View_MyBusesComponent_Host0.createInternal (/DynamicTestModule/MyBusesComponent/host.ngfactory.js:15:32)

........

这是因为 main.ts 似乎没有被加载或执行,我假设 TestBed 是有意这样做的。我没有实际的 Google Analytics 对象当然更好,但是组件确实需要一个名为 ga 的函数。

因此,我的问题如下:如何在我的测试配置中创建 Google Analytics 的 ga 变量,以便它在测试时传递到我的组件?

我已经尝试从我的 mocks 文件中导出一个函数,并将其添加到我的规范文件中的 importsproviders 数组中,但无济于事。

我很感激任何建议!请随时在我上面链接的我们的 repo 协议(protocol)中检查我的代码,并询问您需要的任何后续行动。谢谢!

最佳答案

您声明了 var ga 但这只是为了让 TypeScript 开心。在运行时,ga 由一些外部脚本变成全局的。但是这个脚本没有包含在测试中。

您可以做的只是将 (mock) 函数添加到 window 以进行测试。您可以在 karma-test-shim.js 中执行此操作。

window.ga = function() {}

或者如果您想测试组件是否使用正确的参数调用函数,您可以在使用该函数的每个测试中单独添加该函数。例如

beforeEach(() => {
(<any>window).ga = jasmine.createSpy('ga');
});

afterEach(() => {
(<any>window).ga = undefined;
})

然后在你的测试中

it('..', () => {
const fixture = TestBed.creatComponent(MyBusesComponent);

expect(window.ga.calls.allArgs()).toEqual([
['set', 'page', '/my-buses.html'],
['send', 'pageview']
]);
})

由于您在构造函数中多次调用 gaSpy.calls将获取所有每个调用的参数并将它们放在单独的数组中。

关于unit-testing - ReferenceError : ga is not defined [Ionic 2. 2 使用 Karma 进行单元测试],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43788013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com