gpt4 book ai didi

reactjs - 使用 react-testing-library 运行 Jest 测试时出错

转载 作者:行者123 更新时间:2023-11-28 20:10:25 24 4
gpt4 key购买 nike

这是我第一次写测试。我正在为用钩子(Hook)编写的 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: Cannot read property 'getBarcode' of null

我不知道该如何解决这个问题?

最佳答案

预期是错误的,因为 console.log 没有在任何地方调用。像 global.console = ... 这样模拟 console 对象是一种不好的做法,因为它会在测试之间持续存在并且会破坏依赖它的东西,包括测试运行器本身。

与项目代码键不一致,它是作为条形码提供的。

除非提供默认值,否则上下文值应为 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');

关于reactjs - 使用 react-testing-library 运行 Jest 测试时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54689470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com