簡體   English   中英

React - 在功能組件中測試外部功能

[英]React - Testing external function in a functional component

我有一個使用反應鈎的功能組件。 我有一個更新該組件狀態的函數( 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`, () => "MOCK_RAW", { 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設置為返回undefined的空模擬函數。

由於getChallenge返回調用calculatePerformanceTime的結果,因此它也返回undefined

然后,當這一行運行時:

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

...它試圖將getChallenge(...)的結果用作函數並使用inputs調用它,但是因為它試圖將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`, () => "MOCK_RAW", {
  virtual: true
});

jest.mock(`!raw-loader!../../challenges/2.js`, () => "MOCK_RAW", {
  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}`);
    });
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM