我正在構建一個具有輸入“檔案”型別元素的 React 組件。
export default function NavBar() {
return (
<label htmlFor='upload-image' className={classes.label}> Upload </label>
<input type='file'
id='upload-image'
onChange={ (e) => { uploadImage(e) } } />
)
}
uploadImage是一個獨立的函式,匯出自uploadImage.js:
// uploadImage.js
const uploadImage = async (e) => {
// some code to upload the image to a cloud database
}
export { uploadImage };
使用 Jest 和 React 測驗庫,我正在嘗試測驗是否在輸入“檔案”型別元素更改時觸發 uploadImage。以下是我到目前為止的作業:
import * as uploadImage from '../api/uploadImage';
test("when user changes the file input, uploadImage function is called once", () => {
render( <NavBar /> );
const fileInput = screen.getByLabelText(/Upload/i);
fireEvent.change(fileInput, {
target: {
files: [new File(['(?□_□)'], 'chucknorris.png', {type: 'image/png'})],
},
});
const mock = jest.spyOn(uploadImage, 'uploadImage');
expect(mock).toBeCalled();
});
我希望考試能通過。當 fireEvent.change() 被啟動時,uploadImage 應該被啟動。但是測驗失敗,說明uploadImage沒有被初始化,如下:
expect(jest.fn()).toBeCalled()
Expected number of calls: >= 1
Received number of calls: 0
我懷疑 fireEvent.change() 不起作用,但我不確定。\
- 你能解釋一下為什么測驗沒有通過嗎?
- 對于
uploadImage.js,而不是寫作export { uploadImage },如果我使用匯出默認值,我應該如何使用 jest 來模擬uploadImage,即export default uploadImage?
非常感謝你!
uj5u.com熱心網友回復:
問題是在事件觸發后spyOn呼叫。
將測驗代碼更改為:
test('when user changes the file input, uploadImage function is called once', () => {
render(<NavBar />);
const mock = jest.spyOn(uploadImage, 'uploadImage');
const fileInput = screen.getByLabelText(/Upload/i);
fireEvent.change(fileInput, {
target: {
files: [new File(['(?□_□)'], 'chucknorris.png', { type: 'image/png' })],
},
});
expect(mock).toBeCalled();
});
以便在呼叫模擬函式之前創建并準備好模擬函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/411804.html
標籤:
上一篇:模擬服務人員,悲傷的路徑測驗失敗
