【问题标题】:Extracting JSON in protractor and comparing it with the data send from backend在量角器中提取 JSON 并将其与从后端发送的数据进行比较
【发布时间】:2015-07-01 04:47:40
【问题描述】:

我正在尝试自动化我的前端在 angularjs 中并使用量角器的 Web 应用程序。现在我也想只用量角器进行 api 测试。就像在进行 ajax 调用并获取 JSON 时,从后端发送的数据应该与在前端接收的数据相同。无法找到解决方案。 浏览了很多链接,但没有解决方案。

Accessing $http data in Protractor / E2E tests (AngularJS)

这是我尝试过的-

describe('TestApp',function()
{
    var scope,
            beforeEach(inject(function($rootScope,$controller,$httpBackend){
                scope=$rootScope.$new();
                httpBackend=$httpBackend;
                httpBackend.when("POST","path/to/php/ajax.php").respond([{},{},{}]);

            }));
         it("abc",function(){
             httpBackend.flush();
             expect(scope.data.length).toBe(3);
         });
     });
});

【问题讨论】:

    标签: javascript angularjs automated-tests protractor


    【解决方案1】:

    我花了很多时间试图找到解决这个确切问题的方法。我决定对我来说最好的做法是模拟后端 (https://docs.angularjs.org/api/ngMockE2E/service/$httpBackend) 来拦截 api 调用。 在响应中,我将一个新元素附加到 HTML 页面。然后,您可以将 JSON 放入元素中并从测试中的元素中获取数据。

    $httpBackend.whenPUT(/\/api\/\/.*/).respond(function(method, url, data, headers) {
        var e = document.createElement('div');
        e.setAttribute('class', 'class-name'); //adds an identifier to more easily grab the data
        var jd = JSON.stringify(data); 
        e.innerHTML = JSON.parse(jd); //Creates a JSON to place in the element, the format of data was not a valid JSON
        $('body').prepend(e); //Adds the element to the start of top of the webpage
        return [200, data, {}];
    });
    

    在测试中,调用后,可以简单的抓取带有数据的元素,获取文本进行测试:

    data = element(by.css('.class-name'));
    data.getText().then(function(text){
        expect(text).toMatch(expected, 'Did not match');
    });
    

    这并不理想,需要解决一些问题,但经过长时间的搜索,它提供了我正在寻找的数据。希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多