3

我在 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 } }

这是该测试的正确方法吗?

谢谢


编辑

根据评论进行一些重构。现在我的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并且awaitregister完成函数调用,此时它将填充存储。

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 调用并返回响应。

减速器也被简化为没有任何副作用变化,所以它看起来像:

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

我想我在某处遗漏了一些异步代码,但我无法确定它在哪里。

4

2 回答 2

2

这里有一些 Redux 规则被打破:

  1. 不要在减速器中产生副作用:减速器应该是纯函数:对于相同的输入,总是返回相同的输出。这不是进行 API 调用的地方。
  2. 状态应该是不可变的:你不应该通过引用来改变状态值,总是提供一个新的状态和一个包含变化的新对象。

因此,经典的 redux 方法是在 Redux 中具有三个操作:REGISTER_USER、REGISTER_USER_SUCCEEDED、REGISTER_USER_FAILED。

reducer

const authReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {

        case actionTypes.REGISTER_USER:
            return {
                ...state,
                status: 'loading'
            }
        case actionTypes.REGISTER_USER_SUCCEEDED:
            return {
                ...state,
                status: 'idle',
                user: action.user 
            }
        case actionTypes.REGISTER_USER_FAILED:
            return {
                ...state,
                status: 'error'
            }
        default:
            return state;
    }
}

然后,应该在您的事件处理程序中完成异步工作:

onSubmit

const onSubmit = async data => {
        // ...
        dispatch(registerNewUser());
        const user = new User()
        try {
          await user.register(data);
          dispatch(registerNewUserSucceeded(user));
        } catch(e) {
          console.error(e);
          dispatch(registerNewUserFailed());
        }
    }

**不要忘记在你的 register 函数中从 axios 返回承诺,这样你就可以等待承诺。目前,你只是调用 axios,而不是更新或返回任何东西......

这样做的好处是,测试您的商店不需要您进行任何网络调用!你可以放弃 MSW(虽然它是一个很棒的库,只是这里不需要)。

在您的测试中,只需在每次转换之前和之后检查您的商店状态:

const mockUser = {...} // provide a mock user for your test
const store = createStore(authReducer);
store.dispatch(registerNewUserSucceeded(mockUser);
expect(store.getState()).toEqual({user: mockUser, status: 'idle'});

编辑

为了响应提问者的编辑,由于awaitwith的组合令人困惑,现在有一个错误.then。具体来说,在 中onSubmit,你正在做这两个await并且.then在同一个承诺上。在这种情况下,存在竞争条件。.then调用首先发生,然后发生await。所以而不是await user.register(data).then(...)

const onSubmit = async data => {
    // ...
    try {
        await user.register(data);
    } catch(e) {
        console.log(e);
    }
    dispatch(createNewUser(data));
}

这里我只使用await。try/子句不是catch调用.catch承诺。using让您可以像在编写同步代码一样编写代码,因此只需在表达式之后的下一行await写下您要放入的任何内容。.thenawait

同样在您的注册功能中:

async register(data) {
    try {
        let res = await axios.post(...);
        return res; 
    } catch(e) {
        console.log("error: ", e);
    }
}
于 2021-12-09T17:45:38.383 回答
0

状态不会立即更新,因为服务器调用是一个承诺。您应该等待页面上的某些内容表明该过程已完成,如下所示:

        // Click on the Submit button
        await act(async () => {
            userEvent.click(screen.getByTestId('register-submit-button'));

            await wait(() => getByText('Some text that appears after success '));

            // verify the store was populated
            console.log(await store.getState())
        });

或者你可以等待更新:

        // Click on the Submit button
        await act(async () => {
            userEvent.click(screen.getByTestId('register-submit-button'));
            
            await act(() => sleep(500));

            // verify the store was populated
            console.log(await store.getState())
        });

于 2021-12-03T01:41:10.407 回答