在我的案例中如何模拟 http 请求
How do I mock the http requests in my case
我的单元测试遇到了一个奇怪的问题。
在控制器中我有类似
的东西
testFactory.testFunction($scope.id)
.then(function(returnData) {
// do something with the return
})
出厂档案
test.testFunction = function(id) {
return $http.get('/api/v.10/book/' + id + '/books');
};
单元测试
var books = {data: {id: 333, name: 'my book'}};
beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_, _testFactory_) {
scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_;
testFactory = _testFactory_;
testCtrl = _$controller_('testCtrl', {
$scope: scope
});
$httpBackend.whenGET('/api/v.10/book/333/books').respond(books);
}));
it('should check if test runs', function() {
testFactory.testFunction(333).then(function(returnData){
console.log(returnData)
})
$httpBackend.flush();
})
出于某种原因,console.log 为 'returnData' 将 'books' 变量添加到 objects 并将 headers、status...等添加到响应。
例如:
Object{data: Object{data: Object{id: ..., name: ...}},
status: 200, headers: function (name) { ... },
transformResponse: [...],
url: '/api/v.10/book/333/books', statusText: ''}
我只是期待
{data: {id: 333, name: 'my book''}}
作为我的回应。
有人可以帮我解决这个问题吗?
非常感谢!
当使用带有单个参数的 respond
时,它应该是您想要返回到您的 Web 服务的数据对象 as shown under when
in the docs。因此,您需要将 books
变量更改为 {id: 333, name: 'my book'}
.
我的单元测试遇到了一个奇怪的问题。 在控制器中我有类似
的东西testFactory.testFunction($scope.id)
.then(function(returnData) {
// do something with the return
})
出厂档案
test.testFunction = function(id) {
return $http.get('/api/v.10/book/' + id + '/books');
};
单元测试
var books = {data: {id: 333, name: 'my book'}};
beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_, _testFactory_) {
scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_;
testFactory = _testFactory_;
testCtrl = _$controller_('testCtrl', {
$scope: scope
});
$httpBackend.whenGET('/api/v.10/book/333/books').respond(books);
}));
it('should check if test runs', function() {
testFactory.testFunction(333).then(function(returnData){
console.log(returnData)
})
$httpBackend.flush();
})
出于某种原因,console.log 为 'returnData' 将 'books' 变量添加到 objects 并将 headers、status...等添加到响应。
例如:
Object{data: Object{data: Object{id: ..., name: ...}},
status: 200, headers: function (name) { ... },
transformResponse: [...],
url: '/api/v.10/book/333/books', statusText: ''}
我只是期待
{data: {id: 333, name: 'my book''}}
作为我的回应。
有人可以帮我解决这个问题吗?
非常感谢!
当使用带有单个参数的 respond
时,它应该是您想要返回到您的 Web 服务的数据对象 as shown under when
in the docs。因此,您需要将 books
变量更改为 {id: 333, name: 'my book'}
.