ng mock e2e 意外请求
ng mock e2e Unexpected Request
我在 Angular JS 中开发 UI 时使用 ngMockE2E 模拟 httpBackend。该应用程序在 Grizzly-Server 上运行,后端由虚拟机提供。现在,当我访问网站时,控制台会记录错误:
意外请求:GET /api/info
预计没有更多请求
在我的例子中,我只想模拟一个数据库的数据。除此之外,我想通过一个按钮动态地打开模拟 ON/OFF。这一直有效,直到错误出现。
对于那种情况,我写了以下内容:
$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();
所有面临同样问题的人。我找到了解决该问题的方法。但我相信应该有另一个更好的解决方案。
为此,我使用了 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');
}]);
我在 Angular JS 中开发 UI 时使用 ngMockE2E 模拟 httpBackend。该应用程序在 Grizzly-Server 上运行,后端由虚拟机提供。现在,当我访问网站时,控制台会记录错误:
意外请求:GET /api/info
预计没有更多请求
在我的例子中,我只想模拟一个数据库的数据。除此之外,我想通过一个按钮动态地打开模拟 ON/OFF。这一直有效,直到错误出现。 对于那种情况,我写了以下内容:
$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();
所有面临同样问题的人。我找到了解决该问题的方法。但我相信应该有另一个更好的解决方案。 为此,我使用了 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');
}]);