简体   繁体   中英

Cannot read property 'http' of undefined in test - Angular 2+

Attempting to get a fresh token for my test, but struggling to find the cause...

I'm not sure if this is the best way or whether I should be mocking it, but this is the way I want to do it for now...

The error I am getting is:

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)

this refears to the parent function so if you do

  function getValidToken() {
    return this.http.post(apiBaseUrl + '/auth', postTokenJson)
    .then(map(tok => {
      return tok;
    }));
  }

you will get an error since there's no http function inside getValidToken

the solution is to instanciate the parent 'this' inside a variable like this:

  var pThis=this;
  function getValidToken() {
    return pThis.http.post(apiBaseUrl + '/auth', postTokenJson)
    .then(map(tok => {
      return tok;
    }));
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM