0

有人可以帮助使用反应原生测试来测试 redux 表单提交吗?我正在使用 redux-mock-store 来模拟商店,并且我能够触发事件更改事件。但是我尝试了不同的方法,但不确定如何使用正在传递的值和随后的调度操作调用来测试表单提交。请告知,因为我对这个回声系统比较陌生。

任何人都可以帮助我,因为我对此感到震惊。

这是组件

class Register extends React.Component {
...
submit = (values: RegisterFormProps) => {

    const { register } = this.props;
    console.log('values :', values);
    Keyboard.dismiss();
    const sleep = (ms = 100) => new Promise(resolve => setTimeout(resolve, ms))
    return sleep().then(() => register(values));

  }

render() {
return(<>
...
<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
                <View style={styles.box}>
                  <Field
                    name="firstName"
                    component={UITextInput}
                    ...
                    accessibilityLabel='firstName'
                  />
                  <Field
                    name="lastName"
                    component={UITextInput}
                    ...
                    accessibilityLabel='lastName'
                  />
                  <Field
                    name="email"
                    component={UITextInput}
                    ...
                    accessibilityLabel='email'
                  />
                  <Field
                    name="password"
                    component={UITextInput}
                    secureTextEntry={true}
                    ...
                    accessibilityLabel='password'
                  />
                  <Field
                    name="mobileNumber"
                    component={UITextInput}
                    ...
                    accessibilityLabel='mobileNumber'
                  />
                  <View style={styles.buttonContainer}>
                    <Field
                      name="Register"
                      component={UIButton}
                      onPress={
                        handleSubmit(this.submit)
                      }
                      accessibilityLabel={'registerButton'}
                    />
                  </View>
                </View>
              </TouchableWithoutFeedback>
</>)
}

}

组件的容器

const mapStateToProps = (state: StateProps) => {
  return ({
    isloading: state.user.isLoading,
    token: state.user?.token,
  })
};

const mapDispatchToProps = (dispatch: any) => ({
  register: (user: RegisterFormProps) => dispatch(userRegistration(user))
});



const ReduxComponent = reduxForm<RegisterFormProps>({ form: 'register' })(Component as React.ComponentType<any>);
React.ComponentType<InjectedFormProps<FormProps>>)

const splashContainer = connect(
  mapStateToProps,
  mapDispatchToProps,
)(ReduxComponent);

容器测试

import { renderWithRedux } from './test-utils/render';

const initialState = {
    user: {
        isLoading: false,
        token: '',
    }
};

function renderRegistrationScreen(props: IProps) {
    return renderWithRedux(<Container {...props} />, { initialState });
};

describe('Register', () => {

    const mockSubmit = jest.fn();
    const mockHandleSubmit = jest.fn(); // I tried mock implementation, but the values are not coming thru.

    const props: IProps = {
        componentId: '1',
        isloading: false,
        submit: mockSubmit,
        token: '',
        handleSubmit: mockHandleSubmit,
        register: jest.fn()
    }

    it('register the user', async () => {
        const wrapper = renderRegistrationScreen(props);
        const { getByTestId, getByText, store } = wrapper;
        expect(fireEvent.changeText(getByTestId('firstName'), 'Harry'));
        expect(fireEvent.changeText(getByTestId('lastName'), 'Potter'));
        expect(fireEvent.changeText(getByTestId('email'), 'HP@gmail.com'));
        expect(fireEvent.changeText(getByTestId('password'), 'ABCD123'));
        expect(fireEvent.changeText(getByTestId('mobileNumber'), '0111112222'));
        expect(fireEvent.press(getByText('Register'))); //I've verified that this Register button is pressed
        expect(mockHandleSubmit).toHaveBeenCalledTimes(1);
        expect(mockHandleSubmit).toBeCalledWith('something')// intentionally to check what it returns and it returns [Function bound]
        expect(mockSubmit).toBeCalledWith('...');
        **// Here is what i get struck I want to verify the values that i'm passing in handleSubmit
        // Want to check if the submit function is called if possible
        // Want to check if the dispatch register function is called with right values
        // Is that possible to get the mock payload of the dispatch userRegistration which is called in mapDispatchToProps
        **
        
    });

测试工具/渲染

import { Provider } from 'react-redux';
import { render } from '@testing-library/react-native';
import configureStore from 'redux-mock-store';
import * as thunkMiddleware from 'redux-thunk';

let middlewares = [thunkMiddleware.default];

const logger = require('redux-logger');
// The following logger is added just to confirm the change event - will be removed once tests are working as expected
const loggerMiddleware = logger.createLogger({
  duration: true,
});
middlewares = [...middlewares, loggerMiddleware];

const mockStore = configureStore(middlewares)

export function renderWithRedux(component: any, { initialState }: any = {}) {

  const store = mockStore(initialState);

  const queries = render(<Provider store={store}>{component}</Provider>);

  return {
    ...queries,
    store,
  };
};

布拉德

4

0 回答 0