我正在为自定义应用程序使用 Ionic 框架。在此过程中,我正在尝试为工厂编写单元测试 datastoreServices
它依赖于 DomainService
和 $http
.我对 Jasmine 单元测试的实现感到困惑。
我的工厂如下。
app.factory("datastoreServices", ["$http", function($http) {
return {
getData: function(data, DomainService) {
return $http.post(DomainService.host + 'factor', data);
}
};
}]);
app.factory('DomainService', function() { //here
if (ionic.Platform.isAndroid()) {
return {
host: 'http://10.0.2.2:7001/'
}
}
return {
host: 'http://localhost:7001/'
}
})
我的单元测试框架如下。它有两个依赖项,因此无法弄清楚如何进行。这是我到目前为止在单元测试文件中得到的。
describe(
'datastoreServices',
function() {
beforeEach(module('Myapp'));
describe('getData'),
function() {
it("Should return correct values", inject(function(datastoreServices, DomainService, $httpBackend) {
expect(datastoreServices.getData(httpBackend.. /***something here!**/ )
.toEqual("2.2");
}))
}
我对模拟和其他东西知之甚少。谁能帮我测试那个工厂datastoreServices
.需要测试以下内容:
- Http post 调用正确吗?
- 函数是否返回正确的 promise ?
下面是plnkr中app的类似场景强>。
Idk,如果我要求太多。提前致谢。
最佳答案
主要原则是:
- $http 在测试期间被模拟,这意味着您的服务器在您的测试执行期间并未被实际调用
- 您必须使用 $httpBackend 才能断言 http 调用和模拟服务器响应 https://docs.angularjs.org/api/ngMock/service/ $http后端
- 您可以轻松地注入(inject)或模拟测试所需的任何依赖项
这是一个基于您的 OP 代码的示例:
describe('datastoreServices', function() {
beforeEach(module('MyApp'));
// get a reference to the $httpBackend mock and to the service to test, and create a mock for DomainService
var $httpBackend, datastoreServices, DomainService;
beforeEach(inject(function(_$httpBackend_, _datastoreServices_) {
$httpBackend = _$httpBackend_;
datastoreServices = _datastoreServices_;
DomainService = function() {
return {
host: 'http://localhost:7001/'
};
};
}));
// after each test, this ensure that every expected http calls have been realized and only them
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('calls http backend to get data', function() {
var data = {foo: 'bar'};
// write $http expectation and specify a mocked server response for the request
// see https://docs.angularjs.org/api/ngMock/service/$httpBackend
$httpBackend.expectPOST('http://localhost:7001/factor', data).respond(201, {bar: 'foo'});
var returnedData;
datastoreServices.getData(data, DomainService).success(function(result) {
// check that returned result contains
returnedData = result;
expect(returnedData).toEqual({bar: 'foo'});
});
// simulate server response
$httpBackend.flush();
// check that success handler has been called
expect(returnedData).toBeDefined();
});
});
关于javascript - Jasmine 单元测试具有两个依赖项的 AngularJS 工厂($http 和另一个返回 promise 的工厂),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31660878/