【问题标题】:ng mock e2e Unexpected Requestng mock e2e 意外请求
【发布时间】:2016-06-14 19:14:12
【问题描述】:

在使用 Angular JS 开发 UI 时,我正在使用 ngMockE2E 来模拟 httpBackend。该应用程序在带有由虚拟机提供的后端的灰熊服务器上运行。现在,当我访问网站时,控制台会记录错误:

意外请求:GET /api/info

预计没有更多请求

就我而言,我只想模拟一个数据库的数据。除此之外,我想通过一个按钮即时打开/关闭模拟。这一直有效,直到出现错误。 对于这种情况,我写了以下内容:

$httpBackend.whenPOST(function (url) {
        if (!mockup) {
            return false;
        }
        var target_url = (someUrl);
        return target_url === url;
    }).respond(function (method, url, data) {
        return [200, [someData], {}, 'mockupData'];
    }
);

除此之外,我还添加了以下内容以传递所有其他请求:

// pass the rest of the queries
$httpBackend.whenGET(/.*/).passThrough();
$httpBackend.whenPOST(/.*/).passThrough();
$httpBackend.whenPUT(/.*/).passThrough();
$httpBackend.whenDELETE(/.*/).passThrough();

【问题讨论】:

  • 您是直接从 file:// 使用还是有服务器?如果您使用 from 文件,请尝试安装任何小型 http 服务器,例如节点 http 服务器。因为有一次我在使用 file:// 时遇到了类似的 get 和 mock 问题
  • 它在服务器上运行。所以我认为我的问题有点不同。但是谢谢你的评论。我用你的问题扩展了我的问题。

标签: angularjs mocking ui-testing angular-http-interceptors


【解决方案1】:

所以对于所有面临同样问题的人来说。我找到了解决该问题的方法。但我确信应该有另一个更好的解决方案。 为此,我使用了一个也由 angular 提供的拦截器。 Here the api

所以我写了这个:

app.factory('httpInterceptor', function () {
        return {
            'response': function (response) {
                // therefore you can enable the mockup with a switch or a button
                if (!mockup) {
                    return response;
                }
                try {
                    // in the config object is the requested url
                    if (response.config.url !== someUrl) {
                        // don't intercept; return response unchanged
                        return response;
                    }
                    // found an url which should be mocked
                    // generate or modify the data
                    var generatedData = generateSomeData();
                    response.data.push(generatedData)
                    return response;
                } catch (TypeError) {
                    // don't intercept
                    return response;
                }
            }
        }
    }
);
app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('httpInterceptor');
}]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2015-08-27
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多