我正在使用Ionic框架进行自定义应用程序。在此过程中,我尝试为工厂datastoreServices
编写单元测试,该工厂依赖于DomainService
和$http
。我对Jasmine Unit测试的实现感到困惑。
我的工厂如下。
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
。以下内容需要测试:
以下是 plnkr 中应用的类似情况。
Idk,如果我问得太多了。提前致谢。
答案 0 :(得分:2)
关键原则是:
以下是基于您的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();
});
});