【发布时间】:2022-01-09 11:19:01
【问题描述】:
我在 react 中编写了一个注册组件,它是一个简单的表单,提交时会发布到 API。调用 API 会返回一个带有特定数据的对象,然后这些数据会被添加到 redux 存储中。
我为此写了一些测试。我正在使用 Mock Service Worker (MSW) 来模拟 API 调用。这是我第一次编写此类测试,所以我不确定我是否做错了什么,但我的理解是 MSW 会拦截对 API 的调用并返回我在 MSW 配置中指定的任何内容,之后它应该遵循常规流程。
这是我的减速器:
const authReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case actionTypes.REGISTER_NEW_USER:
const newUser = new User().register(
action.payload.email,
action.payload.firstName,
action.payload.lastName,
action.payload.password
)
console.log("User registered data back:");
console.log(newUser);
return {
...state,
'user': newUser
}
default:
return state;
}
}
这是执行实际调用的我的用户类:
import axios from "axios";
import { REGISTER_API_ENDPOINT } from "../../api";
export default class User {
/**
* Creates a new user in the system
*
* @param {string} email - user's email address
* @param {string} firstName - user's first name
* @param {string} lastName - user's last name
* @param {string} password - user's email address
*/
register(email, firstName, lastName, password) {
// console.log("registering...")
axios.post(REGISTER_API_ENDPOINT, {
email,
firstName,
lastName,
password
})
.then(function (response) {
return {
'email': response.data.email,
'token': response.data.token,
'active': response.data.active,
'loggedIn': response.data.loggedIn,
}
})
.catch(function (error) {
console.log('error');
console.log(error);
});
}
}
这是我的动作创建者:
export function createNewUser(userData) {
return {
type: REGISTER_NEW_USER,
payload: userData
}
}
这是我的注册组件中的onSubmit 方法:
const onSubmit = data => {
// console.log(data);
if (data.password !== data.confirmPassword) {
console.log("Invalid password")
setError('password', {
type: "password",
message: "Passwords don't match"
})
return;
}
// if we got up to this point we don't need to submit the password confirmation
// todo but we might wanna pass it all the way through to the backend TBD
delete data.confirmPassword
dispatch(createNewUser(data))
}
这是我的实际测试:
describe('Register page functionality', () => {
const server = setupServer(
rest.post(REGISTER_API_ENDPOINT, (req, res, ctx) => {
console.log("HERE in mock server call")
// Respond with a mocked user object
return res(
ctx.status(200),
ctx.json({
'email': faker.internet.email(),
'token': faker.datatype.uuid(),
'active': true,
'loggedIn': true,
}))
})
)
// Enable API mocking before tests
beforeEach(() => server.listen());
// Reset any runtime request handlers we may add during the tests.
afterEach(() => server.resetHandlers())
// Disable API mocking after the tests are done.
afterAll(() => server.close())
it('should perform an api call for successful registration', async () => {
// generate random data to be used in the form
const email = faker.internet.email();
const firstName = faker.name.firstName();
const lastName = faker.name.lastName();
const password = faker.internet.password();
// Render the form
const { store } = renderWithRedux(<Register />);
// Add values to the required input fields
const emailInput = screen.getByTestId('email-input')
userEvent.type(emailInput, email);
const firstNameInput = screen.getByTestId('first-name-input');
userEvent.type(firstNameInput, firstName);
const lastNameInput = screen.getByTestId('last-name-input');
userEvent.type(lastNameInput, lastName);
const passwordInput = screen.getByTestId('password-input');
userEvent.type(passwordInput, password);
const confirmPasswordInput = screen.getByTestId('confirm-password-input');
userEvent.type(confirmPasswordInput, password);
// Click on the Submit button
await act(async () => {
userEvent.click(screen.getByTestId('register-submit-button'));
// verify the store was populated
console.log(await store.getState())
});
});
所以我希望只要检测到 REGISTER_API_ENDPOINT url 就会拦截我的调用,并将模拟调用的值添加到我的 redux 状态,而不是 register 方法中的实际 API 调用的值,但这并没有似乎没有发生。如果这不是在商店中测试价值的方法,我还能如何实现呢?
所以在我的测试结束时,在打印我期望看到的商店时:
{ auth: { user:
{
'email': faker.internet.email(),
'token': faker.datatype.uuid(),
'active': true,
'loggedIn': true,
}
}
但我看到的是:
{ auth: { user: null } }
这是本次测试的正确方法吗?
谢谢
编辑
基于 cmets 进行一些重构。现在我的onSubmit 方法看起来像:
const onSubmit = async data => {
if (data.password !== data.confirmPassword) {
console.log("Invalid password")
setError('password', {
type: "password",
message: "Passwords don't match"
})
return;
}
// if we got up to this point we don't need to submit the password confirmation
// todo but we might wanna pass it all the way through to the backend TBD
delete data.confirmPassword
let user = new User()
await user.register(data).
then(
data => {
// console.log("Response:")
// console.log(data)
// create cookies
cookie.set("user", data.email);
cookie.set("token", data.token);
dispatch(createNewUser(data))
}
).catch(err => console.log(err))
请注意,现在我将来自User.register 的响应发送到此处,而不是发送到User.register。另请注意,此函数现在为 async 和 await,以便完成对 register 函数的调用,届时它将填充存储。
register 方法现在如下所示:
async register(data) {
let res = await axios.post(REGISTER_API_ENDPOINT, {
'email': data.email,
'firstName': data.firstName,
'lastName': data.lastName,
'password': data.password
})
.then(function (response) {
return response
})
.catch(function (error) {
console.log('error');
console.log(error);
});
return await res.data;
}
现在它只负责执行 API 调用并返回响应。
reducer 也被简化为没有任何副作用的变化,所以它看起来像:
const authReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case actionTypes.REGISTER_NEW_USER:
const newUser = action.payload
return {
...state,
'user': newUser
}
default:
return state;
}
}
我的测试基本相同,唯一的区别是我正在检查 store 值的部分:
// Click on the Submit button
await act(async () => {
userEvent.click(screen.getByTestId('register-submit-button'));
});
await waitFor(() => {
// verify the store was populated
console.log("Store:")
console.log(store.getState())
})
现在,这有时有效,有时无效。意思是,有时我得到正确的商店打印如下:
console.log
Store:
at test/pages/Register.test.js:219:21
console.log
{
auth: {
user: {
email: 'Selena.Tremblay@hotmail.com',
token: '1a0fadc7-7c13-433b-b86d-368b4e2311eb',
active: true,
loggedIn: true
}
}
}
at test/pages/Register.test.js:220:21
但有时我会收到null:
console.log
Store:
at test/pages/Register.test.js:219:21
console.log
{ auth: { user: null } }
at test/pages/Register.test.js:220:21
我想我在某处遗漏了一些异步代码,但我无法确定它在哪里。
【问题讨论】:
-
当您在浏览器中正常运行您的应用程序时,这行
console.log(newUser);是否记录newUser的正确值?看来您没有从user类中的register方法返回任何内容。 -
@MrCujo 您没有正确等待 onSubmit 处理程序的 xcompletion。根据 gunwin 的回答,也许尝试等待大约 200 毫秒的延迟
-
怎么回事?
await user.register(data)不是等待数据返回的方式吗?老实说,我不认为添加延迟是最好的选择,同步/等待就足够了,我可能肯定做错了,但应该有一个正确的解决方案,只使用同步/等待而不需要添加延迟跨度>
标签: javascript reactjs unit-testing redux msw