[英]Accessing $http data in Protractor / E2E tests (AngularJS)
我有一堆运行良好的单元测试,并且已经开始将Protractor E2E测试添加到我的项目中。 我正在测试页面上的交互元素,但是在测试某些数据从浏览器中发送时遇到了麻烦。
例如,我想查看是否单击某个按钮会生成到某个端点的POST
。
我使用以下方法设置了量角器:
/*globals global*/
module.exports = function() {
'use strict';
var chai = require('chai')
, promised = require('chai-as-promised');
global.expect = chai.expect;
chai.use(promised);
}();
我了解如何使用量角器进行交互:
it('send data to the "log" endpoint when clicked', function() {
var repeater = element.all(by.repeater('finding in data.items'));
repeater.get(0).click().then(function() {
// $http expectation
});
});
但是,我不知道如何在Protractor中设置$httpBackend
,因此我可以捕获由于$httpBackend
.click()
事件.click()
发送的数据。 我需要额外的模块吗?
在Karma / Mocha中,我将简单地:
beforeEach(module('exampleApp'));
describe('logging service', function() {
var $httpPostSpy, LoggingService;
beforeEach(inject(function(_logging_, $http, $httpBackend) {
$httpPostSpy = sinon.spy($http, 'post');
LoggingService = _logging_;
backend = $httpBackend;
backend.when('POST', '/api/log').respond(200);
}));
it('should send data to $http.post', function() [
LoggingService.sendLog({ message: 'logged!'});
backend.flush();
expect($httpPostSpy.args[0][1]).to.have.property('message');
});
});
但是我不知道如何在Protractor中获得对$httpBackend
的引用并inject
模块。
端到端测试是关于测试代码的方式,类似于最终用户的方式。 因此,应根据可见结果验证是否发出了远程请求,例如将数据加载到div或网格中。
仍然,如果您想验证是否发出了远程请求,则可以使用ngMockE2E
模块创建一个模拟后端设置,该模块包含一个类似于$htpBackend
中的模拟$htpBackend
ngMock
。
查看$httpBackend
上的文档https://docs.angularjs.org/api/ngMockE2E/service/ $ httpBackend
$ httpBackend用于模拟对服务器的虚假调用。 在e2e测试中,您通常确实希望实际调用服务器。 重要的是要注意,量角器中的大多数元素定位器都会返回promise 。
这意味着使用此代码,您的测试将知道等待直到服务器的响应返回,然后断言文本p标记是来自服务器的正确数据。
my-file.spec.js
'use strict';
describe('The main view', function () {
var page;
beforeEach(function () {
browser.get('/index.html');
page = require('./main.po');
});
it('should have resultText defined', function () {
expect(page.resultText).toBeDefined()
})
it('should display some text', function() {
expect(page.resultText.getText()
.then())
.toEqual("data-that-should-be-returned");
});
});
my-file.po.js
'use strict';
var MainPage = function() {
this.resultText = element(by.css('.result-text'));
};
module.exports = new MainPage();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.