我是 React 新手。不知怎的,只有我的第一个测试成功了,其余的都失败了。即使我将第二次测试与第一次测试相同,它仍然失败。如果我注释掉第一个测试,第二个测试会成功,然后其余测试会失败,因为无法通过
id
找到组件,并且组件不存在于 DOM 中。
这是我的测试:
describe('Given SomeComponent component', () => {
configure({ testIdAttribute: 'id' });
describe('When trying to render with only id prop set', () => {
const property = {
id: '1',
} as Property;
render(<SomeComponent prop={property} />);
it('Should render successfully', () => {
expect(screen.getAllByTestId('chart-1')).toBeTruthy();
});
});
describe('When trying to render without data prop set', () => {
const property = {
id: '1',
name: 'property of test',
} as Property;
render(<SomeComponent prop={property} />);
it('Should render successfully', () => {
expect(screen.getAllByTestId('chart-1')).toBeTruthy();
});
});
});
测试组件:SomeComponent
export interface Prop {
property: Property;
}
export const SomeComponent = ({ property }: Prop): JSX.Element => {
return (
<>
<div id={`chart-${curveProperty.id}`}>haha</div>
</>
);
};
试试这个:
describe("Given SomeComponent component", () => {
configure({ testIdAttribute: "id" });
it("Should render successfully", () => {
const property = {
id: "1",
} as Property;
const { rerender } = render(<SomeComponent prop={property} />);
expect(screen.getAllByTestId("chart-1")).toBeTruthy();
const newProperty = {
id: "1",
name: "property of test",
} as Property;
rerender(<SomeComponent prop={newProperty} />);
expect(screen.getAllByTestId("chart-1")).toBeTruthy();
});
});
解决方案是使用笑话
test
而不是it
,它开始按我想要的方式工作。
如果从
it
切换到 test
不起作用,因为它不适合我:
如果
<SomeComponent/>
稍微复杂一点,那么在您致电 getAllByTestId
时可能仍有事情发生。就我而言 - 切换到 findAllByTestId
完成了工作,所有测试都按预期通过。
包裹在beforeEach
好吧,我决定在这里补充一下我的经验。将“it”切换为“test”对我没有帮助,基本上据我所知它应该完全相同。
将“getBy”切换为“findBy”也是如此,这对我来说甚至没有意义,因为我没有等待任何数据,这是硬数据。
我正在尝试“afterEach(clean)”,但它现在应该已经过时了(在描述之后自动)。也没有帮助。
我用“beforeEach”解决了这个问题。我还是初学者,所以我不知道到底为什么,但将其包装起来实际上解决了问题,所以也许它也会对其他人有所帮助。
示例:
describe("XXX", () => {
beforeEach(async () => {
render(
<YYY
key={key}
variant={variant}
/>,
{ mocks: [] },
);
});
it("ZZZ", async () => {
expect(screen.getByTestId("test-id")).toBeVisible();
});
});
有了这个,我可以有任意数量的描述,并且它可以清理这些东西。