[英]React final-form I want to handleSubmit only if all fields are valid
[英]Mocking Submit of final-form in react
我正在嘗試通過提交表單來測試是否正在調用回調函數。 我模擬了一個傳遞到 react-final-form 的 onSubmit 函數。 如代碼和框所示,我有一個帶有 onSubmit 回調的簡單表單。
export const MyForm = ({ onSubmit }) => (
<Form
onSubmit={onSubmit}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit} autoComplete="off">
<Field
label="Email"
component={Input}
name="email"
type="email"
autoComplete="off"
/>
<button>Submit</button>
</form>
)}
/>
);
當我在按鈕上模擬點擊事件時,我希望它調用模擬函數。
it("should call onSubmit when the button is click", () => {
const button = wrapper.find("button");
expect(button.length).toBeGreaterThan(0);
button.at(0).simulate("click");
expect(mockSubmit).toHaveBeenCalled();
});
任何幫助將不勝感激。
您需要模擬submit
才能提交表單。
至於Warning: An update to ReactFinalForm inside a test was not wrapped in act(...).
,您在測試中的提交處理程序中使用了 promise,這會導致表單驗證、提交和狀態更新異步。
act()
提供了圍繞預期組件更新的范圍,當組件執行此范圍之外的操作時,您將收到此警告。 由於在測試中提交處理程序是異步的,更新將發生在act()
函數之外,並會給你這個錯誤。
有兩種方法可以解決這個問題,通過jest.fn()
使提交處理程序同步。
const mockSubmit = jest.fn();
如果您需要保持異步,則需要對提交承諾采取行動/等待。 這意味着您需要創建一個已解析的承諾值並讓模擬函數解析它。
const promise = Promise.resolve();
const mockSubmit = jest.fn(() => promise);
beforeEach(() => {
wrapper = mount(<MyForm onSubmit={mockSubmit} />);
});
it("should call onSubmit when the button is click 2", async () => {
const button = wrapper.find("form");
expect(button.length).toBeGreaterThan(0);
button.at(0).simulate("submit");
expect(mockSubmit).toHaveBeenCalled();
await act(() => promise);
});
我的首選方法是使用<button type="submit">Submit</button>
然后fireEvent.click(getByText('Submit'))
, 就像這樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.