【问题标题】:How to write unit test for function that calls React.UseEffect in it ( code included )如何为其中调用 React.UseEffect 的函数编写单元测试(包括代码)
【发布时间】:2021-09-24 08:20:09
【问题描述】:

Scroll.js

import React from "react";

export const ScrollToTop = ({ children, location }) => {
  React.useEffect(() => window.scrollTo(0, 0), [location.pathname]);
  return children;
};

Scroll.test.js

import React from "react";
import { ScrollToTop } from "./ScrollToTop";

describe("ScrollToTop", () => {
  it("", () => {
    expect(
      ScrollToTop({
        children: "some children",
        location: { pathname: "the path" }
      })
    ).toEqual();
  });
});

我得到的结果是 enter image description here

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs enzyme


    【解决方案1】:

    你不应该直接调用ScrollToTop作为一个函数,这就是错误信息所抱怨的。

    React docs 推荐 Testing Library 编写测试。

    以下是如何使用上述库编写Scroll.test.js 的示例:

    import React from "react";
    import { render } from '@testing-library/react';
    import { ScrollToTop } from "./ScrollToTop";
    
    describe("ScrollToTop", () => {
      it('calls window.scrollTo()', () => {
        window.scrollTo = jest.fn(); // create a moack function and record all calls
        render(<ScrollToTop location={{ pathname: 'pathname' }}>Text</ScrollToTop>); // render a component
    
        expect(window.scrollTo).toHaveBeenCalledWith(0, 0); // check that scrollTo mock was called
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-06-25
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多