reactjs 使用React测试库或Jest测试依赖于上下文的组件

e1xvtsh3  于 2023-01-12  发布在  React
关注(0)|答案(2)|浏览(149)

我的所有组件都从Context中获取数据和方法。我想测试--至少--“组件呈现”用例,但是当然,当我试图在测试用例中呈现组件时,它找不到来自Context的方法/函数和数据。我找不到使用React Testing Library或Jest(我需要使用这些库,而不是酶)将Context值传递给测试用例的方法。
假设我想测试一个简单的Filter组件。
上下文(我猜是原始用法)

import { useState, useEffect, createContext } from "react";

const Context = createContext();

const ContextProvider = ({ children }) => {
  const [books, setBooks] = useState([]);
  // other data and method code..

  const handleFilter = (value) => {
    const filteredBooks = [...books];
    if (books.length > 0) {
      switch (value) {
        case "alphabetical":
          filteredBooks.sort((a, b) => a.title - b.title);
          setBooks(filteredBooks);
          break;
        case "publishdate":
          filteredBooks.sort(
            (a, b) => b.first_publish_year - a.first_publish_year
          );
          setBooks(filteredBooks);
          break;
        default:
          setBooks(filteredBooks);
      }
    }
  };

  return (
    <Context.Provider value={{ handleFilter }}>
      {children}
    </Context.Provider>
  );
};

export { ContextProvider, Context };

过滤器

import { useContext } from "react";
import { Context } from "../context/Context";

function Filter() {
  const { handleFilter } = useContext(Context);

  return (
    <div className="filter" data-testid="filter-test">
      <div className="filter-content">
        <select
          defaultValue="none"
          className="filter-btn"
          onChange={(e) => handleFilter(e.target.value)}
        >
          <option value="none" defaultValue disabled>
            Filter Results
          </option>
          <option value="alphabetical">Alphabetically</option>
          <option value="publishdate">Publish Date (newest)</option>
        </select>
      </div>
    </div>
  );
}

export default Filter;

Filter.test.js

import { render, screen, cleanup } from '@testing-library/react';
import Filter from './Filter';

test('renders Filter component without crashing', () => {
  // I need to pass handleFilter function using Context somehow
  render(<Filter />);
  const filterComponent = screen.getByTestId('filter-test');
  expect(filterComponent).toBeInTheDocument();
});

如果您想查看所有代码:https://codesandbox.io/s/inspiring-bhaskara-0s98g

rkue9o1l

rkue9o1l1#

简单的方法是将上下文提供器作为render()的第一个参数的 Package 器传递:

import { render, screen, cleanup } from '@testing-library/react';
import Filter from './Filter';

// import your context; it will include the provider
import { Context } from "../context/Context";

test('renders Filter component without crashing', () => {
  const contextValue = { handleFilter: () => {} };
  render(
    <Context.Provider value={contextValue}>
      <Filter />
    </Context.Provider>
  );

  const filterComponent = screen.getByTestId('filter-test');
  expect(filterComponent).toBeInTheDocument();
});

另一种方法是将上下文作为 Package 器提供给呈现:

import { render, screen, cleanup } from '@testing-library/react';
import Filter from './Filter';

// import your context; it will include the provider
import { Context } from "../context/Context";

test('renders Filter component without crashing', () => {
  const contextValue = { handleFilter: () => {} };
  const wrapper = ({ children }) => (
    <Context.Provider value={contextValue}>
      {children}
    </Context.Provider>
  );

  render(<Filter />, { wrapper });

  const filterComponent = screen.getByTestId('filter-test');
  expect(filterComponent).toBeInTheDocument();
});

以上两种方法都可以

5n0oy7gb

5n0oy7gb2#

最简单的方法是添加一个对象作为render方法的第二个参数。如果该对象的 wrapper 属性如下所示,则将上下文提供程序组件指定为值:

render(<MyComponent />,{ wrapper: ContextProvider})

下面是一篇博客文章,很好地解释了如何正确:beingdev.online

相关问题