我有一個 Jest 單元測驗,它正在測驗來自模擬 API 呼叫的錯誤,以確保錯誤訊息顯示在頁面上。在我的實際檔案中,我notistack用來顯示錯誤訊息。我沒有顯示完整的 API 請求,因為我認為它不相關,簡而言之,如下:
myComponent.js:
import { useSnackbar } from 'notistack';
const myComponent = props => {
const { enqueueSnackbar } = useSnackbar()
//make an API call to an endpoint
...
if (response.ok) enqueueSnackbar("API Success", { variant: "success" });
else enqueueSnackbar("API Failed", { variant: "error" });
}
因此,我正在單元測驗中測驗上述內容。同樣,我不會粘貼整個單元測驗,因為我認為它不相關,但類似于:
myComponent.test.js
import { render, screen } from "@testing-library/react"
test("testing error message on API call", async () => {
// mock the API call to return a 500 <- this works fine
render(<myComponent />)
// ensure that the error message is displayed in the screen
expect(screen.queryByText(/API Failed/)).toBeInTheDocument();
});
執行上述操作,我得到一個錯誤:
TypeError:無法解構“(0,_notistack.useSnackbar)(...)”的屬性“enqueueSnackbar”,因為它未定義
如果我簡單地包含以下內容,enqueueSnackbar()將被定義但測驗仍然失敗,因為訊息是null.
const mockEnqueue = jest.fn();
jest.mock('notistack', () => ({
...jest.requireActual('notistack'),
useSnackbar: () => {
return {
enqueueSnackbar: mockEnqueue
};
}
}));
但是,我什至不想模擬快餐欄,因為我想測驗每個特定場景的實際顯示訊息(有多個)。
uj5u.com熱心網友回復:
render()在我的單元測驗中包裝SnackbarProvider解決了這個問題。
import { SnackbarProvider } from "notistack"
import { render, screen } from "@testing-library/react"
test("testing error message on API call", async () => {
/* mock the API call to return a 500 <- this works fine */
render(
<SnackbarProvider>
<myComponent />
</SnackbarProvider>
)
/* ensure that the error message is displayed in the screen */
expect(screen.queryByText(/API Failed/)).toBeInTheDocument();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416273.html
標籤:
上一篇:分離應用程式和包測驗時的匯入問題
下一篇:開玩笑地解決回圈依賴
