【发布时间】:2019-07-08 10:11:45
【问题描述】:
这是我第一次编写测试。我正在为使用钩子编写的 ReactJS 应用程序编写测试,并使用 Jest 和 react-testing-library 进行测试。
这是我的功能组件:
const ItemDetails = ({ item }) => {
const { code } = item;
const { getBarcode } = useStationContext();
return (
<>
<Button
type="primary"
onClick={() => {
getBarcode(code);
}}
style={{ float: 'right' }}
>
Print Barcode
</Button>
<List
bordered
dataSource={formatData(item)}
renderItem={({ title, value }) => (
<List.Item>
<List.Item.Meta
description={
<Wrapper>
<p>{upperCase(title)}</p>
<div>{value}</div>
</Wrapper>
}
/>
</List.Item>
)}
/>
</>
);
};
export default ItemDetails;
和测试文件:
import React from 'react';
import { render, cleanup } from 'react-testing-library';
import ItemDetails from '../containers/Items/ItemPage/ItemDetails';
afterEach(cleanup);
describe('formatData()', () => {
it('Return Details about item', async () => {
const { getByText, getByTestId, container, asFragment } = render(
<ItemDetails
item={{
id: '296-c-4f-89-18',
barcode: 'E-6',
}}
/>,
);
global.console = {
log: jest.fn(getByText, getByTestId, container, asFragment),
};
expect(global.console.log).toHaveBeenCalledWith('test');
});
});
当我运行测试时,我得到了这个错误:
TypeError: 无法读取 null 的属性“getBarcode”
我不知道如何解决这个问题?
【问题讨论】:
-
这可能取决于 useStationContext 是什么。请为您的案例提供stackoverflow.com/help/mcve。
-
这是一个上下文。
标签: reactjs testing jestjs react-testing-library