我的数据测试id在那里,但我的测试找不到它反应酶笑话单元测试



我对用jest和酶进行单元测试还是个新手,我有一个数据测试id,我正在尝试使用它进行单元测试。然而,我收到一个错误,说没有找到数据测试id。

我有以下

import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import { configure, mount, shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';
import ConfirmationModal from '../src/components/GlobalForm/ConfirmationModal/ConfirmationModal';
configure({ adapter: new Adapter() });
describe('ConfirmationModal', () => {
it('should be defined', () => {
expect(ConfirmationModal).toBeDefined();
});
it('should render correctly', () => {
const tree = mount(<ConfirmationModal />);
expect(shallowToJson(tree)).toMatchSnapshot();
});
it('should have a cancel button', () => {
const wrapper = shallow(<ConfirmationModal />);
const ConfirmationModalComponent = wrapper.find("[data-test-id='cancel-submit-btn']");
expect(ConfirmationModalComponent.length).toBe(1);
});
});

甚至我的快照测试也显示我有这个数据测试id

exports[`ConfirmationModal should render correctly 1`] = `
<confirmationModal>
<Styled(div)>
<div
className="css-d2ogfy"
>
<Styled(div)>
<div
className="css-ywnjte"
>
Confirm your submission
</div>
</Styled(div)>
<Styled(p)>
<p
className="css-1v1a1rr"
>
The submission of your changes will directly affect the call center with which they are assigned.
</p>
</Styled(p)>
<Styled(p)>
<p
className="css-1v1a1rr"
>
Are you sure that you want to proceed with these changes?
</p>
</Styled(p)>
<Styled(div)>
<div
className="css-wqsxq7"
>
<Button
dataTestId="cancel-submit-btn"
name="Cancel"
>
<Styled(button)
data-test-id="cancel-submit-btn"
>
<button
className="css-2ba12r"
data-test-id="cancel-submit-btn"
>
Cancel
</button>
</Styled(button)>
</Button>
<Button
dataTestId="confirm-submit-btn"
name="Confirm"
>
<Styled(button)
data-test-id="confirm-submit-btn"
>
<button
className="css-2ba12r"
data-test-id="confirm-submit-btn"
>
Confirm
</button>
</Styled(button)>
</Button>
</div>
</Styled(div)>
</div>
</Styled(div)>
</confirmationModal>
`;

但我的测试结果有错误:

ConfirmationModal›应该有一个取消按钮

expect(received).toBe(expected) // Object.is equality
Expected: 1
Received: 0

如何????就在那里。。。

因为这个问题是我在谷歌上搜索数据测试和酶时第一个出现的。

试试这个:

wrapper.find({ "data-testid": "cancel-submit-btn" }).simulate("click");

这篇博客文章详细介绍了反应酶快照测试。我添加了上面的例子,以防博客文章被删除。

不确定您的ConfirmationModal组件是什么样子的,但我猜它像您的快照所示那样封装了一些样式:<Styled(div)>

在你的快照测试和你试图找到data-test-id的测试之间,第一个测试安装了组件,而第二个测试只是浅层渲染它,因此我猜你的最后一个测试,如果你检查快照,确实不会有整个组件,而是可能是这样的:

<confirmationModal>
<Styled(div) />
</confirmationModal>