这是我第一次写测试。我正在为用钩子编写的ReactJS应用程序编写测试,并使用取笑和反应-测试-库进行测试。
这是我的功能组件:
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:无法读取属性'getBarcode‘的null
我不知道怎样才能解决这个问题?
发布于 2019-02-14 12:22:55
预期是错误的,因为console.log在任何地方都没有被调用。模拟console对象(如global.console = ... )是一种糟糕的做法,因为它在测试之间持续存在,并且可以破坏依赖它的东西,包括测试运行程序本身。
它与项目code密钥不一致,它以barcode的形式提供。
除非提供默认值,否则预期上下文值为undefined。它应该在试验中提供。
可能应该是:
const getBarcodeMock = jest.fn();
const { getByText, getByTestId, container, asFragment } = render(
<StationContext.Provider value={{ getBarcode: getBarcodeMock }}>
<ItemDetails
item={{
id: '296-c-4f-89-18',
code: 'E-6',
}}
/>
</StationContext.Provider>
);
// ...simulate button click...
expect(getBarcodeMock).toBeCalledWith('E-6');https://stackoverflow.com/questions/54689470
复制相似问题