2016-12-16 53 views
0

我正在使用量角器以便在我的应用程序中进行一些端到端测试。在测试中,我嘲笑后端的呼叫与MockModule如下:量角器覆盖“beforeAll”http模拟

describe('Lets test a feature' , function(){ 
    beforeAll(function() { 
     var customerE2E = function() { 
      angular.module('customerE2E', ['customer', 'ngMockE2E']) 
       .run(function ($httpBackend) { 

        $httpBackend.whenPOST('/api/data').respond(200); 
        $httpBackend.whenGET(/^.*/).passThrough(); 
      }); 
     }; 
     browser.addMockModule('customerE2E', customerE2E); 
    }); 

    it('correctly demonstrates my problem', function() { 
     expect(element(by.css('h4')).getText()).toMatch('Hello world'); 
    }  
}) 

这工作确实不错,但我的问题是,我也想测试我的应用程序时,后有404,500等响应我已经通过为每种情况提供了一个新的“describe”功能来解决这个问题,但是能够从“it”函数中覆盖此调用会很好。

it('correctly demonstrates my problem', function() { 
    expect(element(by.css('h4')).getText()).toMatch('Hello world'); 
} 

it('show error due to bad request', function() { 
    /* 
    Replace $httpBackend.whenPOST('/api/data').respond(200); 
    with $httpBackend.whenPOST('/api/data').respond(404); 
    */ 
    expect(element(by.css('h4')).getText()).toMatch('Failed api call'); 
} 

我真的很新的这个,所以我想知道如果有一个很好的方式来实现一个简单的方法来覆盖这是在beforeAll功能设置较早MockModuled。

回答

2

您可以使用beforeEach()来实现它。

describe('Test Mock Module',function() { 

    var statusCodes = [200,404,500]; 
    var currentTestNumber = 0; 
    beforeAll(function() { 
     var customerE2E = function() { 
      angular.module('customerE2E', ['customer', 'ngMockE2E']) 
       .run(function ($httpBackend) { 

        $httpBackend.whenPOST('/api/data').respond(200); 
        $httpBackend.whenGET(/^.*/).passThrough(); 
       }); 
     }; 
     browser.addMockModule('customerE2E', customerE2E); 
    }); 

    /*Below method will be executed before each test and set the required response respectively*/ 
    beforeEach(function() { 
     $httpBackend.whenPOST('/api/data').respond(statusCodes[currentTestNumber++]); 
    }); 

    it('test 200 status code',function() { 
     expect(element(by.css('h4')).getText()).toMatch('Message for 200 status code'); 
    }); 

    it('test 404 status code',function() { 
     expect(element(by.css('h4')).getText()).toMatch('Message for 404 status code'); 
    }); 

    it('test 500 status code',function() { 
     expect(element(by.css('h4')).getText()).toMatch('Message for 500 status code'); 
    }); 
}); 
+0

你甚至试过这个吗?因为它在模块中使用,所以我无法从beforeEeach中获得$ httpBakend。这可以通过在beforeEech中创建一个新的customerE2E来解决,但这看起来很难看,我也无法访问变量statusCodes和CurrentTestNumber – willedanielsson