使用jest在react测试中模拟仅用于特定测试的子组件



我的应用程序(根组件(看起来像这个

<div>
<button>Click Me</button>
<ChildComponent/>
</div>

在我的应用程序组件测试文件(App.test.js(中,我有两个测试。我希望在1测试中模拟ChildComponent,但在第二测试中使用实际的ChildComponent实现。

在App.test.js的顶部放一个jost.mock("./components/ChildComponent"(,可以模拟文件中的所有测试。

如果你能以一个小的工作例子作为回应,我将不胜感激。

提前谢谢。

describe("Tests for App Component", ()=>{
it("Test 1",()=>{
// Use Actual Child Component implmeentation in this test  
})
it("Test 2",()=>{
// Use mocked Child Component here as the assertions are not related to the Child Component here, assertions only check the button and other components in App.js
})
})

最简单的方法是将测试文件拆分为2个。因此,您将能够在一个中模拟jest.mock('./components/ChildComponent',,并在另一个中使用真正的child。

另一种选择是尝试使jest.doMockjest.unmock适用于您的案例,但我不确定这是否有效。它肯定会让测试的代码变得混乱和混乱,没有任何实际价值。谁在乎呢,它是每个组件的唯一测试文件还是两个?

最新更新