我有一个名为 Product 的 React 组件,如下所示:
<div>
<Wrapper>
<Heading>{props.headerText}</Heading>
<Service>({props.items.length})</Service>
</Wrapper>
{props.items !== undefined && props.items.length > 0 ? (
<TableWrapper>
{props.items &&
props.items.length > 0 && (
<DataTable paginationSize={props.paginationSize}>
<DataTable.Heading accessor="name"> Name </DataTable.Heading>
<DataTable.Heading accessor="id"> Service ID </DataTable.Heading>
<DataTable.Heading accessor="type"> Access </DataTable.Heading>
<DataTable.Heading accessor="band"> Band </DataTable.Heading>
<DataTable.Heading accessor="noUsers"> Users </DataTable.Heading>
{props.tableItems.map((p, i) => {
return <DataTable.Row key={i} data={p} />;
})}
</DataTable>
)}
</TableWrapper>
) : (
<NoMessage>{props.noItemMessage}</NoMessage>
)}
</div>
其中 Wrapper、Heading、Service、TableWrapper 是样式组件。我正在尝试 使用 Jest 和 Enzyme 测试此组件,以检查 headerText 道具是否正确呈现 。下面给出的代码是我尝试编写测试用例的方式:
test("header text is being passed through correctly", () => {
const wrapper = mount(
<Product items={data} headerText="Service" paginationSize="5" noItemMessage="No results found" />
);
expect(wrapper.find(HeaderText).text()).toEqual("Service");
但我收到此错误:
TypeError: Cannot read property 'blue' of undefined
at Object.<anonymous>.exports.RightArrow.Icons.RightArrow.extend.props (src/lib/DataTable.js:149:129)
DataTable.js 中的第 149 行是:
color: ${props => props.theme.secondary.blue};
我无法弄清楚为什么会出现此错误。有人可以指导我解决这个问题吗?我只是想检查 headerText 是否从 props 中正确渲染。
在包装器中添加主题作为道具
<Product
items={data}
theme={{secondary: {blue: ''}}}
headerText="Service"
paginationSize="5"noItemMessage="No results found" />
或者嘲笑它
import { createSpy } from 'expect';
const theme = createSpy();
<Product
items={data}
theme={theme}
headerText="Service"
paginationSize="5"
noItemMessage="No results found" />
我们可以使用 styled-componnets 的 themeProvider 来创建一个围绕
shallow
或 mount
酶方法的包装器,如下所示:
import { ThemeProvider } from 'styled-components';
const mountWithTheme = (children, theme={}, options = {}) => {
const wrapper = mount(<ThemeProvider theme={theme}>{children}</ThemeProvider>, options);
return wrapper.mount({});
};
test("header text is being passed through correctly", () => {
const wrapper = mountWithTheme(<Product items={data} headerText="Service" paginationSize="5" noItemMessage="No results found" />,
{ secondary: { blue: 'blue' } });
// we passed the theme we want as an argument to the mountWithTheme method
expect(wrapper.find(HeaderText).text()).toEqual("Service");
});
最好将 utils mountWithTheme 和 ShallowWithTheme 提取到不同的文件中,以便可以重用它,并且作为建议,您可以创建一个模拟主题文件,其中包含一些可以传递给这些包装器的默认主题,而不是每次我们使用这些实用程序时手动传递主题。
更多信息,请访问以下链接: https://github.com/styled-components/styled-components/issues/1319