簡體   English   中英

如何在反應中使用 Jest 模擬單元函數

[英]How to mock unit functions using Jest in react

我的渲染方法中有以下代碼

render() {
let isNew = Boolean(domService.getQueryParamByName("isNew"));
if(isNew) {
return(
// soemthing
)} else {
return(// return anything)

現在如何在 jestUnit 測試用例中模擬 getQueryParamByName 單元函數,使其覆蓋 if 塊。

如果你將 domService 從另一個文件導入到你的組件,在測試中你可以像這樣添加一個間諜:

//component.test.js
import domService from "relative-path";

const mockFunction = jest.fn((obj) => {});

beforeEach(() => {
    mockFunction.mockClear();
    jest.spyOn(domService,"getQueryParamByName").mockReturnValue(mockFunction);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM