unit-testingfetchfunctional-testingfetch-mock

How do I fetch-mock a post request with a payload


I am using the wheresrhys fetch-mock npm module to run functional testing in my app. I would like to mock a fetch with method 'POST' and a specific payload.

It would look something like this:

fetchMock.mock({
        routes: {
            name: 'LoginSuccess',
            matcher: "https://myurl",
            method: 'POST',
            payload: {
                params:{User: "ABCDE@gmail.com", Password: "password"}
            },
            response: {  
                result:{
                    message: "Successful login", 
                    credentials: "XXXXXXXXXXXXX"
                }
            }
        }
    });

I would like to check the payload of my fetch and give a response correspondingly. For example I could simulate one login where the user submits the wrong password, then they try again and submit the correct info and are granted access. Same url, different payloads, different responses.

Is it possible to do this? I know it's possible to check the method of the fetch, but I'd like to do the same with payload.

Or is there a better way to do this?

I haven't found a solution in the readme of the module or in the test section of the fetch-mock package.


Solution

  • fetchMock.mock({
        routes: [{
                name: 'LoginSuccess',
                matcher: function(url, opts) {
                    return (url=="https://myurl" && opts && opts.params && opts.params.User=="ABCDE@gmail.com" && opts.params.Password=="password");
                },
                response: {  
                    result:{
                        message: "Successful login", 
                        credentials: "XXXXXXXXXXXXX"
                    }
                }
            }, {
                name: 'LoginFail',
                matcher: function(url, opts) {
                    return (url=="https://myurl" && opts && opts.params && opts.params.User=="ABCDE@gmail.com" && opts.params.Password!=="password");
                },
                response: { 
                    result:{
                        message: "Unsuccessful login"
                    }
                }
        }]
    });