使用jest

时间:2017-10-25 12:43:37

标签: reactjs react-redux jest

我正在尝试使用类似于此文件的某些代码测试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函数。

    已调用预期的模拟函数。

1 个答案:

答案 0 :(得分:11)

这是我使用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