5

我正在使用 wheresrhys fetch-mock npm 模块在我的应用程序中运行功能测试。我想使用“POST”方法和特定的有效负载来模拟获取。

它看起来像这样:

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"
                }
            }
        }
    });

我想检查我的 fetch 的有效负载并相应地给出响应。例如,我可以模拟用户提交错误密码的登录,然后他们再试一次并提交正确的信息并被授予访问权限。相同的 url,不同的有效载荷,不同的响应。

是否有可能做到这一点?我知道可以检查 fetch 的方法,但我想对有效负载做同样的事情。

还是有更好的方法来做到这一点?

我在模块的自述文件或fetch-mock 包的测试部分中没有找到解决方案。

4

1 回答 1

3
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"
                }
            }
    }]
});
于 2016-05-03T09:07:00.603 回答