如何将变量从浏览器传递给Protractor

时间:2015-10-28 19:16:09

标签: angularjs http protractor angularjs-e2e e2e-testing

我正在测试单个页面应用程序,该应用程序向给定的api端点发出GET请求,期望得到一些结果。

现在,我使用$ httpbackend对象模拟了API,我需要断言正确的URL传递给它(执行GET requet时)。

我的网址包含API需要知道的许多额外信息(startTime,endTime等)。我只想测试传递正确的东西。

这是我目前的端到端测试:

var chai = require('chai');
var chaiPromise = require("chai-as-promised");
var HttpBackend = require('http-backend-proxy');
var utils = require('../utils.js');
var expect = chai.expect;
var dateTimeSupport = require('../dateTimeFillSupport.js');
var support = require('../uhhSupport.js');
chai.use(chaiPromise);


var steps = function(){
    var proxy = null;
    var urlFound = "";

    this.Before(function(event, callback){
        proxy = new HttpBackend(browser);
        callback();
    }); 

    this.After(function(event, callback){
        proxy.onLoad.reset();
        callback();
    });



    this.Given(/^my given$/, function(){
        // Set up the context for the proxy - to be able to pass stuff back and forth
        var simpleChartData = require('data.json');
        proxy.context = {
            chartData   : simpleChartData,
            foundUrl    : urlFound
        };

        // Allow components and directived to pass through
        proxy.onLoad.whenGET(/\.\/components\/.+/).passThrough();
        proxy.onLoad.whenGET(/directives\/.+/).passThrough();           
        proxy.onLoad.whenGET(/.+\/api\/pvValues\/.+/).respond(function(method, url){
            $httpBackend.context.foundUrl = url;
            return [200, $httpBackend.context.chartData];
        });

            // perform action
        browser.get(utils.baseUrl);
        $('.dateLabel').click();

        return browser.controlFlow().execute(function(){});
    });

    this.When(/^a card is clicked$/, function(){        
        return dateTimeSupport.clickTheFirstCard().then(function(){
            $('.etChart').isDisplayed();
        });
    });

    this.Then(/^the correct URL is passed to the mocked API$/, function(){
    var expectedUrl = "myexpectedurl";
// here I want to check expectedUrl against $httpBackend.context.foundUrl
            return browser.controlFlow().execute(function(){});
        });
    }

    module.exports = steps;

所以问题是,如何将$httpBackend.context.foundUrl变量传递给我的then函数? (为了查看ti是否与预期的URL匹配?)

1 个答案:

答案 0 :(得分:2)

您可以在respond内的Given函数中将全局变量写入浏览器窗口:

proxy.onLoad.whenGET(/.+\/api\/pvValues\/.+/).respond(function(method, url){
        window.foundUrl = url;
        return [200, $httpBackend.context.chartData];
    });

Then中,您可以让浏览器执行脚本以将全局返回到量角器:

    this.Then(/^the correct URL is passed to the mocked API$/, function(){
        var expectedUrl = "myexpectedurl";
        // here I want to check expectedUrl against $httpBackend.context.foundUrl
        return browser.executeScript('return window.foundUrl').then(function(theUrl){
            expect(theUrl === expectedUrl).to.be.true;
        });
    });