【发布时间】:2016-08-28 13:43:05
【问题描述】:
我正在尝试通过 jasmine 设置 http GET 请求预期,但出现以下错误:
TypeError: Cannot read property 'user' of undefined
我要测试的服务功能如下:
function getData() {
return $http.get('http://example.com/data')
.then(function (response) {
return response.data.example.user;
});
}
对 URL“http://example.com/data”的 GET 请求会返回以下数据:
{
"id": "1",
"example": {
"user": [
{
"name": "John",
"wife": [
{
"name": "Jane",
"age": "27"
}
]
}
}
}
对应的测试如下所示:
describe("Service: myService", function () {
beforeEach(module("myApp"));
var myService, $httpBackend;
beforeEach(inject(function (_myService_, _$httpBackend_) {
myService = _myService_;
$httpBackend = _$httpBackend_;
$httpBackend.whenGET("http://example.com/data").respond("some data");
}));
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("should call the correct URL", function() {
$httpBackend.expectGET("http://example.com/data");
myService.getData();
$httpBackend.flush();
});
一旦服务函数(我想测试的)返回嵌套的 JSON 属性而不是整个 JSON,我就无法测试 http GET 请求。
提前致谢!
【问题讨论】:
标签: angularjs json jasmine typeerror httpbackend