是否有明确的方法来测试 React 组件是否返回另一个已构建的自定义组件?

问题描述 投票:0回答:2

例如,

ComponentA.tsx:

const ComponentA = () => {
    return (
        <>
        <ComponentB/>
        </>
    )
}

ComponentA.test.tsx

describe("ComponentA", () => {
    it("Calls ComponentB in render", () => {
        render(<ComponentA/>);
        const componentB = <ComponentB/>;
        expect(componentB).toHaveBeenCalledTimes(1);
    });
});

试过上面的方法还是失败了。我希望类似的东西会起作用,并且我尝试了上述的其他变体,但仍然没有通过测试。曾经有一个例子,我在 expect 周围用 waitFor 运行了类似的东西并且它通过了,但是通过的测试没有正确通过。

reactjs typescript unit-testing jestjs tdd
2个回答
0
投票

toHaveBeenCalled(..)
与模拟函数一起工作。

为了测试

ComponentA
正在调用
ComponentB
,您创建一个模拟
ComponentB
函数并实例化
<ComponentA/>

const ComponentA = () => {
    return (
        <>
        <ComponentB/>
        </>
    )
}

// Create mock function
const ComponentB = jest.fn();

describe("ComponentA", () => {
    it("Calls ComponentB in render", () => {
        render(<ComponentA/>);
        expect(ComponentB).toHaveBeenCalledTimes(1);
    });
});

0
投票

给 ComponentB 一个

aria-label
然后在你的测试中获取任何带有该标签的元素并使用
expect(element).toBeInTheDocument();
或类似的东西。

顺便说一句,这是可访问性的良好做法。因为如果元素像它们应该的那样支持可访问性,那么它们还应该具有轻松识别它们是否在 DOM 中的方法。这是您编写的测试用例的目的之一。甚至可以将一些 lint 规则添加到您的环境中以检查可访问性。

© www.soinside.com 2019 - 2024. All rights reserved.