我在React/TypeScript中有以下代码:
const logUser = async () => {
console.log(`Logging: ${email} - ${password}`);
try {
const res = await axios({
method: "post",
url: `${process.env.REACT_APP_BASE_URL}/api/auth`,
headers: {
"Content-Type": "application/json",
"Accept-Language": localStorage.getItem("i18nextLng"),
},
data: {
email: email,
password: password,
},
});
const user = buildUserData(res.data.data);
saveUserData(user.name, user.email, user.roles, user.token);
setDismissAlert(true);
console.log(res.data);
login().then(() => navigate("/dashboard/overview"));
} catch (err: any) {
if (err.response?.data.otp) {
navigate("/otp", { state: { email: email, password: password } });
} else if (err.data?.data.message) {
setLoginError(err.data?.data.message);
setDismissAlert(false);
} else {
setLoginError(t("login.validation.loginError"));
setDismissAlert(false);
}
}
};
在我的测试中,除了axios.post.mockResolvedValueOnce();返回成功请求所期望的内容,下面几行内容就不包括在内:
const user = buildUserData(res.data.data);
saveUserData(user.name, user.email, user.roles, user.token);
setDismissAlert(true);
console.log(res.data);
login().then(() => navigate("/dashboard/overview"));
我尝试用这种方式返回模拟数据:
const mockResponse = {
data: {
user: {
id: 1,
name: "user",
email: "user@mail.com",
email_verified_at: null,
created_at: "2022-12-27T17:10:23.000000Z",
updated_at: "2022-12-27T17:10:29.000000Z",
deleted_at: null,
last_login_at: "2022-12-27T17:10:29.301355Z",
roles: ["user"],
},
token: {
access_token: "1|Buc8kgCTGFzHdS2HU11ZmWS30SEXHEiLCEQGbBnH",
token_type: "Bearer",
},
},
};
在我的测试中:
axios.post.mockResolvedValueOnce(mockResponse);
但这不会解决未覆盖的行。
我需要做些什么来覆盖try块(而不是catch)中axios请求之后的行?
1条答案
按热度按时间wnvonmuf1#
试试这个-而不是使用这个API:
使用此:
然后在测试中: