使用量角器运行测试时调用其他API [英] Call other api when running tests using Protractor
问题描述
我目前已使用量角器进行了一些测试.这些测试正在从WebApi检索数据.但是,我想将WebApi调用指向一个真实但经过模拟的WebApi,该WebApi仅返回要用作测试数据的对象.
I currently have setup some tests using protractor. These tests are retrieving data from a WebApi. However, I want to point the WebApi calls to a real but mocked WebApi that just returns the objects I want to use as test data.
例如,当前请求为:
http://localhost/myApp/api/profile/getUser/1
我想操纵此请求,以便测试使用:
I want to manipulate this request so the test will use:
http://localhost/myApp/apiMock/profile/getUser/1
首先,我想编写一个可以更改请求标头的拦截器,但是我不知道如何使它与Protractor一起工作.我不能在量角器测试中直接使用角度,可以吗?如果可以的话,编写拦截器不是问题,我只是不知道如何将其插入量角器进行测试.
First I thought to write an interceptor that changes the request header but I don't have a clue how to make this work with Protractor. I can't use angular directly within my protractor tests, can I? If I can, writing the interceptor isn't a problem, I just don't know how to plug it in for my tests in protractor.
我已阅读以下帖子:端到端和模拟,但是它不能满足我的需求,因为我不想一遍又一遍地调用同一网址,我想替换动态网址(的一部分)以指向模拟的api服务.
I've read the following post: E2E and Mocking but it doesn't fulfill my needs as I don't want to call the same url over and over again, I want to replace (part of) the dynamic url to point to the mocked api service.
只是为了让自己更清楚一点,我不是在客户端上寻找模拟数据.我想保留API调用(我认为这是更多的E2E),但只指向另一个返回模拟数据的API URL.
Just to make myself more clear, I'm not looking for mocked data on the client side. I want to keep the API calls (in my opinion it's more E2E) but just point to another API url that returns mocked data.
推荐答案
可以通过添加addMockModule
此处有更多详细信息:量角器addMockModule和$ httpProvider拦截器
more details here: Protractor addMockModule and $httpProvider interceptor
解决方案:
exports.apiMockModule = function () {
console.log('apiMockModule executing');
var serviceId = 'mockedApiInterceptor';
angular.module('apiMockModule', [])
.config(['$httpProvider', configApiMock])
.factory(serviceId,
[mockedApiInterceptor]);
function mockedApiInterceptor() {
return {
request: function (config) {
console.log('apiMockModule intercepted');
if ((config.url.indexOf('api')) > -1) {
config.url = config.url.replace('api/', 'apiMock/');
}
return config;
},
response: function (response) {
return response
}
};
}
function configApiMock($httpProvider) {
$httpProvider.interceptors.push('mockedApiInterceptor');
}
};
然后在加载模块的地方进行实际测试.
Then I have my actual test where I load the module.
describe('E2E addMockModule', function() {
beforeEach(function() {
var mockModule = require('./mockedRest');
browser.addMockModule('apiMockModule', mockModule.apiMockModule);
console.log('apiMockModule loaded');
browser.get('#page');
});
it('tests the new apiMock', function() {
// your test that clicks a button that performs a rest api call.
});
});
信用归@gontard
Credits go to @gontard
这篇关于使用量角器运行测试时调用其他API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!