javascript – 在Protractor / E2E测试中访问$http数据(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);
}();

我理解如何使用Protractor进行交互:

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,这样我就可以捕获由于.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');
    });
});

但我不知道如何获得$httpBackend的引用并在Protractor中注入模块.

解决方法

端到端测试是关于测试代码的方式与最终用户的方式类似.因此,验证是否进行远程请求应该针对可见结果进行验证,例如将数据加载到div或网格中.

仍然如果要验证远程请求,您可以使用ngMockE2E模块创建模拟后端设置,该模块包含类似于ngMock中的模拟$htpBackend.

查看$httpBackend https://docs.angularjs.org/api/ngMockE2E/service/ $httpBackend上的文档

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...