【问题标题】:Adding the properties to the window object and using it before the import of components将属性添加到窗口对象并在导入组件之前使用它
【发布时间】:2020-09-03 06:35:01
【问题描述】:

我有一个 Home 组件,所以我正在为该组件编写一个测试用例,问题出在 Home 组件内部我需要一个 config.js 文件和多个组件,它们在其中使用 config.js

该文件基本上是应用程序的配置。

所以值来自window._config_ 对象,所以要在我的测试用例中添加属性。我尝试了以下方法。

import React from "react";
import { mount, shallow } from "enzyme";
import Home from "..";

describe("Home Page", () => {
    beforeEach(() => {
        window._config_ = {
            URL: "http://www.sample.com",
        };
    });
    it("should render Home Page", () => {
        console.log("here", window._env_);
        const wrapper = shallow(<Home />);
        expect(wrapper).toMatchSnapshot();
    });

});

所以由于 Home 组件是在顶部导入的,它会导入 相关的配置文件,因为只有在描述块内我才添加 属性

在上述情况下,我收到的错误为TypeError: Cannot read property 'URL' of undefined

如果我评论 Home 组件它的工作,所以我尝试在 'it' 块内导入 Home,但导入应该在顶层完成,所以我尝试使用常见的 js 要求方式,但这给了我以下错误:

it("should render Home Page", () => {
    console.log("here", window._env_);
    const Home = require("..");
    const wrapper = shallow(<Home />);
}


ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was `object`.

我正在为 React 应用程序使用 CRA。

我应该如何解决这个问题?

更新

也试过this,但我应该如何添加它,当我在全局中添加窗口时它说

Out of the box, Create React App only supports overriding these Jest options:

  • collectCoverageFrom
  • coverageReporters
  • coverageThreshold
  • coveragePathIgnorePatterns
  • extraGlobals
  • globalSetup
  • globalTeardown
  • moduleNameMapper
  • resetMocks
  • resetModules
  • snapshotSerializers
  • transform
  • transformIgnorePatterns
  • watchPathIgnorePatterns.

These options in your package.json Jest configuration are not currently supported by Create React App:

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:

    终于找到了,可以在setupTests.js中添加全局变量

    import { configure } from "enzyme";
    import Adapter from "enzyme-adapter-react-16";
    
    global.config = {
        URL: "http://www.example.com",
    };
    configure({ adapter: new Adapter() });
    

    在每个测试文件中你都可以像这样访问

    it("should render Home Page", () => {
            console.log("here", window.config.URL);
            const wrapper = shallow(<Home />);
            expect(wrapper).toMatchSnapshot();
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 2019-12-27
      • 2017-06-11
      • 2018-03-14
      • 1970-01-01
      • 2018-05-28
      相关资源
      最近更新 更多