javascript-React-测试功能组件中的外部功能

前端之家收集整理的这篇文章主要介绍了javascript-React-测试功能组件中的外部功能 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个使用react挂钩的功能组件.我有一个更新该组件状态的函数(evaluateFunction).

此更新状态函数调用用于检索数据的外部函数,如下所示:

import { calculatePerformanceTime } from "../../helpers/calculate-performance-time";

const getChallenge = challengeNumber =>
    calculatePerformanceTime(
        require(`../../../challenges/${challengeNumber}.js`)[
            `dcpChallenge${challengeNumber}`
        ],challengeNumber
    );

export const TestComponent = _ => {
    const [inputs,setInputs] = useState({});
    const [result,setResult] = useState({});
    const evaluateFunction = value => setResult(getChallenge(value)(inputs));
    return (
        <div>
          <button onClick={() => evaluateFunction(1)} />
        </div>
    );
};

当我模拟单击以测试是否调用了calculatePerformanceTime时,会引发以下错误

TypeError: getChallenge(...) is not a function

我尝试导出getChallenge,但没有成功.

如何在单击按钮时测试该函数是否已被调用

到目前为止,这是我一直在测试的内容

import React from "react";
import Adapter from "enzyme-adapter-react-16";
import { configure,shallow } from "enzyme";
import { ChallengeSolution } from "./ChallengeSolution";
import { calculatePerformanceTime } from "../../helpers/calculate-performance-time";
configure({ adapter: new Adapter() });

const mockFunction = jest.fn();
const mockInputData = 1;

jest.mock(`!raw-loader!../../challenges/1.js`,() => "MOCK_RAW",{
    virtual: true
});

jest.mock(`!raw-loader!../../challenges/2.js`,{
    virtual: true
});

jest.mock("../../helpers/calculate-performance-time.js");

describe("ChallengeSolutionComponent",() => {
    let wrapper;
    const tabNumber = 2;
    beforeEach(() => {
        wrapper = shallow(<ChallengeSolution selectedTab={tabNumber} />);
    });

    describe("when component was mount",() => {
        it("should render form correctly",() => {
            const title = wrapper.find(".challenge-solution__title");
            const button = wrapper.find(".challenge-solution__button");
            button.simulate("click");
            expect(calculatePerformanceTime).toHaveBeenCalled();
            expect(title.text()).toEqual(`Daily Coding Solution #${tabNumber}`);
        });
    });
});
最佳答案
这行:

jest.mock("../../helpers/calculate-performance-time.js");

…将calculatePerformanceTime设置为返回未定义的空模拟函数.

由于getChallenge返回调用calculatePerformanceTime的结果,因此它也返回未定义.

然后,当此行运行时:

const evaluateFunction = value => setResult(getChallenge(value)(inputs));

…它尝试将getChallenge(…)的结果用作函数并通过输入调用它,但是失败了,因为它试图将undefined调用函数.

您需要模拟calculatePerformanceTime以返回一个函数

import React from "react";
import Adapter from "enzyme-adapter-react-16";
import { configure,shallow } from "enzyme";
import { ChallengeSolution } from "./ChallengeSolution";
import * as calculatePerformanceTimeModule from "../../helpers/calculate-performance-time";  // import the module
configure({ adapter: new Adapter() });

const mockFunction = jest.fn();
const mockInputData = 1;

jest.mock(`!raw-loader!../../challenges/1.js`,{
  virtual: true
});

jest.mock(`!raw-loader!../../challenges/2.js`,{
  virtual: true
});

const spy = jest.spyOn(calculatePerformanceTimeModule,'calculatePerformanceTime');
spy.mockReturnValue(() => { /* this returns a function...fill in the return value here */ });

describe("ChallengeSolutionComponent",() => {
  let wrapper;
  const tabNumber = 2;
  beforeEach(() => {
    wrapper = shallow(<ChallengeSolution selectedTab={tabNumber} />);
  });

  describe("when component was mount",() => {
    it("should render form correctly",() => {
      const title = wrapper.find(".challenge-solution__title");
      const button = wrapper.find(".challenge-solution__button");
      button.simulate("click");
      expect(spy).toHaveBeenCalled();  // Success!
      expect(title.text()).toEqual(`Daily Coding Solution #${tabNumber}`);
    });
  });
});

猜你在找的JavaScript相关文章