【发布时间】:2013-07-25 09:37:58
【问题描述】:
是否可以在模拟 $httpBackend 中覆盖或重新定义模拟响应?
我有这样的测试:
beforeEach(inject(function ($rootScope, $controller, _$httpBackend_) {
$httpBackend = _$httpBackend_;
//Fake Backend
$httpBackend.when('GET', '/myUrl').respond({}); //Empty data from server
...some more fake url responses...
}
这在大多数情况下都很好,但我很少有测试需要为同一个 URL 返回不同的东西。但是似乎一旦定义了 when().respond() 之后,我就无法在这样的代码中更改它:
单个特定测试中的不同反应:
it('should work', inject(function($controller){
$httpBackend.when('GET', '/myUrl').respond({'some':'very different value with long text'})
//Create controller
//Call the url
//expect that {'some':'very different value with long text'} is returned
//but instead I get the response defined in beforeEach
}));
我该怎么做? 我的代码现在无法测试:(
【问题讨论】:
-
我已经通过将单元测试分成 2 个文件来“解决”它。每个文件都有自己的 $httpBackend.when().respond() 定义。这是一个丑陋的解决方案,但到目前为止我没有找到更好的解决方案。
-
我在使用 http 的 ng-describe 模拟时遇到了同样的问题,例如 github.com/kensho/ng-describe#mock-httpget - 它似乎在它使用
$httpBackend.when(...)的引擎盖下,当我后来想要deps.$httpBackend.expect("POST", "foobar")并断言deps.$httpBackend.verifyNoOutstandingExpectation();我收到一个错误Error: Unsatisfied requests: POST foobar。似乎使用 ng-describe$http模拟使得以后无法使用httpBackend.expect()。
标签: unit-testing angularjs mocking