我是新来的从事自动化测试的人,所以我尝试进行一些单元测试,我建立了一个通常的自定义钩子来处理表单事件和输入更改。
import { useState } from 'react'
const useFormHook = (callback) => {
const [inputs, setInputs] = useState({});
const handleSubmit = (e) => {
if (e) {
e.preventDefault();
}
setInputs({})
callback();
}
const handleInputChange = (e) => {
e.persist();
setInputs(inputs => ( {...inputs, [e.target.name]: e.target.value } ));
}
return{
handleSubmit,
handleInputChange,
inputs
}
}
export default useFormHook
,实现进入搜索栏,该事件将更新上下文状态,如下所示:
const SearchBar = () => {
const [search, setSearch] = useState('')
useAsyncHook(search); // I'm using an async custom hook to fetch some data with axios.
const handleFormSubmit = () => {
let targetValue = Object.values(inputs).join().toLowerCase()
setSearch(targetValue)
document.forms[0].reset()
}
const { inputs, handleSubmit, handleInputChange } = useCustomFormHook(handleFormSubmit)
return (
<form onSubmit={handleSubmit} className="searchForm">
<input
id='searchBar'
type="text"
name="value"
value={inputs.value || ''}
onChange={handleInputChange}
required
className={`input`}
/>
<input
className={`button primary`}
type="submit"
value="? Search"
id='search-button'
/>
</form>
)
}
到现在为止一切正常。.
import React from "react";
import { mount, shallow } from "enzyme";
//components and hooks
import useFormHook from "../../../Services/Hooks/customFormHook";
//import useAsyncHook from "../../../Services/Hooks/customAsyncHook";
//import SeachBar from "../SearchBar";
describe("Custom hooks suite test", () => {
// const wrapper = shallow(<SeachBar />);
let results;
const handleHookTester = (hook) => {
function HookWrapper() {
results = hook();
return null;
}
mount(<HookWrapper />);
return results;
};
it("Form hook test", () => {
handleHookTester(useFormHook);
expect(results.inputs).toStrictEqual({});
});
});
到目前为止,我设法使它起作用,但这只是customFormHook,我想测试一下,而我的customAsyncHook如下所示:
const useAsyncHook = (id) => {
const [loading, setLoading] = useState('false');
const { findData } = useContext(AppContext)
// 1 -
useEffect(() => {
async function getData() {
try {
setLoading('true');
const response = await axios(
`someEndPoint/${id}`
);
findData({type:FIND_DATA, data:response.data });
} catch (error) {
setLoading('null');
findData({type:FIND_DATA, data:null });
}
}
if (id !== "") {
getData();
}
}, [id]);
return loading;
}
,如果我尝试使用类似const wrapper = shallow(<SearchBar/>)
或:
handleHookTester(useAsyncHook);
测试失败并引发以下错误:
● Custom hooks suite test › encountered a declaration exception
TypeError: Cannot destructure property 'findData' of '(0 , _react.useContext)(...)' as it is undefined.
8 | const [loading, setLoading] = useState('false');
9 |
> 10 | const { findData } = useContext(AppContext)
| ^
11 | // 1 -
12 | useEffect(() => {
所以问题是我应该模拟那个功能吗?以及如何?