酶参考错误 - 无法访问窗口功能

时间:2017-05-03 10:32:55

标签: reactjs mocha enzyme jsdom

我在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/>);
    });
});

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

1 个答案:

答案 0 :(得分:1)

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

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

window.getString = () => {};

b)如果要测试其调用

,则getString存根sinon

sinon.stub(window, 'getString');

c)在测试中包含main.js

import './main.js';