[英]How do I mock an imported function in jest?
我目前有一個要測試的反應組件,如下所示(名為 BigDemo):
import {Demo, DemoProps} from ...
*/lots of helper functions*/
export function BigDemo(props: BigDemoProps): h.JSX.Element {
const TheseDemoProps: DemoProps<ItemType> = {
items: //Array of items,
helperFunction,
helperFunction,
etc. with more helper functions
}
return <Demo {...TheseDemoProps} />;
}
我想測試所有輔助函數是否都有效,但它們不是導出函數。
當我使用以下測試時,Demo 組件基本上是空的,並且沒有提供任何輔助函數的測試覆蓋率。 我應該如何更改它以使用我自己的代碼來模擬 Demo 組件,該代碼利用道具來測試輔助函數?
jest.mock(//path to Demo);
import {Demo} from '//path to Demo';
const MockedDemo = jest.mocked(Demo);
describe('Testing Demo', () => {
function renderWrap(): void {
const items = ...;
render(
<div testid="root">
<BigDemo items={items} />
</div>
{wrapper}
);
root = screen.getByTestId('root')
}
it('should render the component', () => {
renderWrap();
expect(MockedDemo).toBeCalledTimes(1); //This works
expect(root.querySelector(/*name of a class that a helper function should
define*/)).not.toBeNull(); //this fails
}
}
不確定我是否真的理解你的問題。 如果是這樣,您應該導入為: import * as Demo from '//path to Demo'
;
然后模擬它,例如: const MockedDemo = jest.mocked(Demo.BigDemo);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.