gpt4 book ai didi

reactjs - 使用 jest 进行 Redux 表单测试

转载 作者:行者123 更新时间:2023-12-03 13:33:16 25 4
gpt4 key购买 nike

我正在尝试测试 redux 表单提交的一些类似于此文件的代码。

https://github.com/marmelab/admin-on-rest/blob/master/src/mui/auth/Login.js

我的代码是这样的

  const middlewares = [];
const mockStore = configureMockStore(middlewares);

it("submit button", () => {
userLogin = jest.fn();
const initialState = {
admin: {
notification: {
text: "",
type: "info"
}
},
};
store = mockStore(initialState);
tn = label => label;

const props = {
submitting: false,
theme: customTheme,
translate: tn,
store,
location: {
state: {
nextPathname: "/"
}
},
userLogin: userLogin
};
container = mount(
<Provider store={store}>
<TranslationProvider locale="en">
<Login {...props} /> //Login is connected component
</TranslationProvider>
</Provider>
,
{
context: { store: mockStore(initialState) }
}
);
const username = container.find("TextField").first();
username.simulate("change", { target: { value: "admin" } });
const password = container.find("TextField").last();
password.simulate("change", { target: { value: "Superuser" } });

const form = container.find("form");
form.simulate("submit");
console.log(username.debug());

expect(userLogin).toHaveBeenCalled();
});

我面临两个问题。

  1. 当我打印用户名时,我看不到通过模拟更新的更新值。
  2. 其次,expect 子句失败。如何确保代码中的 userLogin 函数被调用。

    预期已调用模拟函数。

最佳答案

这就是我使用 JEST 快照测试来测试 redux-forms 的方法。

import React from 'react'
import renderer from 'react-test-renderer'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import YourReduxFormComponent from 'path where it sitting in your project'
import { reduxForm } from 'redux-form'

jest.mock('react-dom')

const spy = jest.fn()
const initialStateValues = {/* initial state values that your form component expects */}
const Decorated = reduxForm({
form: 'testForm', onSubmit: { spy }
})(YourReduxFormComponent)

const formFieldValues = {/*Form field values*/}

it('YourReduxFormComponent renders correctly', () => {
const store = createStore((state) => state, initialStateValues)
const tree = renderer.create(
<Provider store={store}>
<Decorated
{...formFieldValues}
/>
</Provider>
).toJSON()
expect(tree).toMatchSnapshot()
})

//Make your own tests like above to test the values

关于reactjs - 使用 jest 进行 Redux 表单测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46932791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com