Din*_*ota 12 javascript unit-testing jasmine angularjs ionic
我正在使用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/'
}
})
Run Code Online (Sandbox Code Playgroud)
我的单元测试骨架如下.它有两个依赖关系,因此无法弄清楚如何继续.这是我到目前为止在单元测试文件中得到的.
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");
}))
}
Run Code Online (Sandbox Code Playgroud)
我对嘲笑和东西知之甚少.有人可以帮我测试那家工厂吗datastoreServices
?以下内容需要测试:
这是plnkr中app的类似场景.
Idk,如果我问得太多了.提前致谢.
主要原则是:
这是一个基于您的操作代码的示例:
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();
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1618 次 |
最近记录: |