测试反应组件 axios 发布请求

时间:2021-03-31 15:49:52

标签: reactjs testing jestjs jest-mock-axios

我有一个 React 组件,它向 recipes/search 端点发送我的 api 请求。

const recipeSearch = ({ setRecipes }) => {
    const [flavorType, setFlavorType] = useState({
        flavor_type: 'Sour',
    });

    const { flavor_type } = flavorType;

    const [loading, setLoading] = useState(false);

    const onChange = (e) => setFlavorType({ ...flavorType, [e.target.name]: e.target.value });

    const onSubmit = (e) => {
        e.preventDefault();

        const config = {
            headers: {
                'Content-Type': 'application/json',
            },
        };

        setLoading(true);
        axios
            .post(
                `${process.env.REACT_APP_API_URL}/recipes/search/`,
                {
                    flavor_type,
                },
                config
            )
            .then((res) => {
                setLoading(false);
                setRecipes(res.data);
                window.scrollTo(0, 0);
            })
            .catch(() => {
                setLoading(false);
                window.scrollTo(0, 0);
            });
    };

    return (
        <div data-testid='RecipeSearch'>
            <form onSubmit={(e) => onSubmit(e)}>
                <div>
                    <div>
                        <div>
                            <label htmlFor='flavor_type'>Choose Flavor</label>
                            <select name='flavor_type' onChange={(e) => onChange(e)} value={flavor_type}>
                                <option value='Sour'>Sour</option>
                                <option>Sweet</option>
                                <option>Salty</option>
                            </select>
                        </div>

                        <div>
                            {loading ? (
                                <div>
                                    <Loader type='Oval' color='#424242' height={50} width={50} />
                                </div>
                            ) : (
                                <button type='submit'>Search</button>
                            )}
                        </div>
                    </div>
                </div>
            </form>
            <div>{testing}</div>
        </div>
    );
};

recipeSearch.propTypes = {
    setRecipes: PropTypes.func.isRequired,
};

export default recipeSearch;

提交表单时,调用 onSubmit 函数,该函数又将请求发布到我的后端 api

axios
            .post(
                `${process.env.REACT_APP_API_URL}/recipes/search/`,
                {
                    flavor_type,
                },
                config
            )

我想测试请求确实发送到了正确的网址。

我正在使用 React 测试库,想知道使用 jest-mock-axios 库执行此操作的正确方法是什么

0 个答案:

没有答案
相关问题