簡體   English   中英

在量角器/端到端測試(AngularJS)中訪問$ http數據

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM