使用axios对提交进行反应测试 [英] React testing onSubmit using axios

查看:177
本文介绍了使用axios对提交进行反应测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始测试我的React应用。但是,在处理提交表格时我偶然发现了。我的测试涵盖了大部分行,但错过了提交表单方法的实际部分

I recently started testing my React app. However, I stumbled when dealing with submitting forms. My test covers most of the lines but misses out on actual part of submit form method.


LoginForm.js - 提交表格



          const userLoginData = {
              userId : this.state.userId,
              password : this.state.password,
              userType : this.state.userType
          };

          axios({
              data : JSON.stringify(userLoginData),
              type : 'post',
              url : Constant.BASE_URL_SERVER+'/rest/login',
              headers : {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json'
              },
              cache : false
           })
           .then(function (response) {
              //alert("Form Submitted.");
              this.setState({isLoggedIn : true});
              this.setState({loginResponse : "Login Success!"});
              if(this.state.userType === 'Customer'){
    ...




login_form-test.js



        describe('testing form submission onSubmit', () => {
            const testData = {
                userId: '00000000',
                password: 'SamplePassword0',
                userType: 'Customer',
                validForm: true,
            }

            it('should submit form onSubmit()', () => {
                const mountedComponentHandle = mount(<LoginForm {...testData}/>);
                const onSubmitForm = sinon.spy(
                    mountedComponentHandle.instance(),
                    'handleSubmitForm'
                );
                mountedComponentHandle.update();
                const formHandle = mountedComponentHandle.find('form');
                expect(formHandle.length).toBe(1);

                formHandle.simulate('submit');
                expect(onSubmitForm.called).toBe(true);
            });
        });

请建议如何测试 .then() .catch() of axios。

Please suggest on how to test .then() and .catch() of axios.

谢谢。

推荐答案

这里的关键是让你的代码可测试。分离责任有助于使您的代码更易于测试,易读且易于维护。在你的情况下,通过API发布数据的逻辑在于一些服务,它将处理你的应用程序的api请求,你可以单独测试。

回到你的问题,我给你一个在您的情况下测试异步调用的可能解决方案:

Key here is to make your code "testable". Separating responsibility helps to make your code more testable, readable and easy to maintain. In your case logic to post data over an API lies in some service which will handle api requests for your app, and you can test it separately.
Coming back to your question, I am providing you one of the possible solutions for testing async calls in your case:

// apiGateway.js
const postData = (url, data) => (
    axios({
        data: JSON.stringify(data),
        type: 'post',
        url: BASE_URL_SERVER + url,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        cache: false
    })
);

再次,你可以单独测试上面的代码。

Again you can test above code separately.

// myAppApi.js
const postLoginForm = (data, callback, errorCallback) => {
    return postData('/rest/login', data)
        .then((response) => callback(response.data))
        .catch((error) => errorCallback(error))

};

// myAppApi.test.js
// import * as myAppApi from '../myAppApi'
it('should call callback when response is successful', async () => {
    const mockResponse = {};
    const mockRequestData = {};
    const mockSuccessCallback = jest.fn();
    const mockErrorCallback = jest.fn();

    spyOn(myAppApi, 'postLoginForm').and.returnValue(Promise.resolve(mockResponse));

    await myAppApi.postLoginForm(mockRequestData, mockSuccessCallback, mockErrorCallback);

    expect(mockSuccessCallback).toHaveBeenCalled();
});

it('should call error callback when response is failed', async () => {
    const mockRequestData = {};
    const mockSuccessCallback = jest.fn();
    const mockErrorCallback = jest.fn();

    spyOn(myAppApi, 'postLoginForm').and.returnValue(Promise.reject());

    await myAppApi.postLoginForm(mockRequestData, mockSuccessCallback, mockErrorCallback);

    expect(mockErrorCallback).toHaveBeenCalled();
});

在上述测试中,您可以使用不同的模拟方法或库。

最后你的组件看起来像这样

In above tests you can use different mocking methods or libraries.
And finally your component will look something like this

// LoginForm.js
class LoginForm extends React.Component {
    onSuccessfulLogin(responseData) {
        //.. success logic here
    }

    onFailedLogin(error) {
        //.. error logic here
    }

    onSubmitForm(event) {
        postLoginForm(this.state.data, this.onSuccessfulLogin, this.onFailedLogin)
    }
}

正如您所看到的,分离逻辑有助于测试。此外,它还可以帮助您避免使用包含大量代码的组件。您可以测试组件的状态和演示。

希望这可以回答您的问题!

As you can see separating out logic helps in testing. Further it will save you from ending up with component with tons of code in it. You can test your component for its state and presentation.
Hope this answers your question!

这篇关于使用axios对提交进行反应测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆