【问题标题】:Enzyme reference error - unable to access window functions酶参考错误 - 无法访问窗口函数
【发布时间】:2017-10-01 03:20:25
【问题描述】:

我在main.js中有以下函数(加载了node.exe):

window.onload = () => {
    window.getString = function () {
        <Do something>
        return value;
    };
}

以下是我使用 Enzyme 和 Mocha 编写的测试用例

import "jsdom-global/register";
import React from "react";
import {mount} from "enzyme";
import Sessions from "./Sessions";
describe("Testing Sessions Page", () => {
    it('should work', () => {
        let wrapper = mount(<Sessions/>);
    });
});

在使用 React 框架编写的 Sessions 组件中,我使用 getString 方法。当我运行我的测试时,它给出了ReferenceError: getString is not defined。如何使测试代码中的窗口对象可访问?

【问题讨论】:

    标签: reactjs mocha.js enzyme jsdom


    【解决方案1】:

    由于您使用的是jsdom-global,因此定义了窗口对象但未定义getString,因此:

    a) 在您的测试中,在 describe 块之前定义 getString 方法:

    window.getString = () =&gt; {};

    b) 存根 getStringsinon 如果你想测试它的调用

    sinon.stub(window, 'getString');

    c) 只需在您的测试中包含 main.js

    import './main.js';

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-20
      • 1970-01-01
      相关资源
      最近更新 更多