我的所有组件都从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
2条答案
按热度按时间rkue9o1l1#
简单的方法是将上下文提供器作为
render()
的第一个参数的 Package 器传递:另一种方法是将上下文作为 Package 器提供给呈现:
以上两种方法都可以
5n0oy7gb2#
最简单的方法是添加一个对象作为render方法的第二个参数。如果该对象的 wrapper 属性如下所示,则将上下文提供程序组件指定为值:
下面是一篇博客文章,很好地解释了如何正确:beingdev.online