无法读取测试中未定义的属性“ http”-Angular 2+

时间:2018-08-01 09:08:33

标签: javascript angular types

试图为我的测试获取新的令牌,但努力寻找原因...

我不确定这是最好的方法还是我应该嘲笑它,但这是我现在想做的方法...

我得到的错误是:

TypeError: Cannot read property 'http' of undefined
        at getValidToken src/app/services/auth/auth.service.spec.ts:15:17)
        at Suite.<anonymous> src/app/services/auth/auth.service.spec.ts:31:22)
        at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)
        at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run node_modules/zone.js/dist/zone.js:138:1)
        at Suite.<anonymous> node_modules/zone.js/dist/zone-testing.js:491:1)
        at Env.jasmineEnv.(anonymous function) [as fdescribe] node_modules/zone.js/dist/zone-testing.js:424:1)
        at Object../src/app/services/auth/auth.service.spec.ts src/app/services/auth/auth.service.spec.ts:8:1)

1 个答案:

答案 0 :(得分:2)

function getValidToken() { return this.http.post(apiBaseUrl + '/auth', postTokenJson) .then(map(tok => { return tok; })); } 会返回父函数,所以如果您这样做

http

由于getValidToken中没有 var pThis=this; function getValidToken() { return pThis.http.post(apiBaseUrl + '/auth', postTokenJson) .then(map(tok => { return tok; })); } 函数,您会得到一个错误

解决方案是在这样的变量中实例化父级“ this”:

{{1}}