2016-07-18 11 views
0

私は認証サービスを模擬しようとしています。私はログイン資格証明を掲示し、トークンを取り戻し、次にトークンを保存します。依存関係がありません:未定義のプロパティ 'saveToken'をスローすることはできません

私は行をコメント場合は基本的にテストが実行されます。

this.authenticationService.saveToken(res.json().token); 

私はテストでサービスを注射し、そしてこの行は出力には影響を与えません。

私のエラーはここ

は私のサービスである "スロー未定義のプロパティを読み取ることができません 'saveToken'" である:ここでは

private authSuccess(res: Response){ 
    this.isAuthenticated = true; 
    this.authenticationService.saveToken(res.json().token); 
    return res.json(); 
} 

public postLogin(loginData: LoginModel): Observable<any>{ 
    let body = JSON.stringify(loginData); 
    var headers = new Headers();   
    headers.append('Content-Type', 'application/json'); 
    let options = new RequestOptions({ headers: headers }); 

    return this.http.post(this.loginUrl, body, options) 
    //success 
    .map(this.authSuccess) 
    //error   
    .catch(this.handleError);   
} 

は私のテストで:

describe('login service tests',() => {  
    let loginService: LoginService; 
    let backend: MockBackend; 
    let injector: Injector; 
    let authenticationService: AuthenticationService; 

    beforeEach(() => { 
    injector = ReflectiveInjector.resolveAndCreate(<any> [ 
     LoginService, 
     AuthenticationService, 
     BaseRequestOptions, 
     MockBackend, 
     provide(Http, { 
      useFactory: (mockBackend, defaultOptions) => new Http(mockBackend, defaultOptions), 
      deps: [MockBackend, BaseRequestOptions] 
     }) 
    ]); 

    loginService = <LoginService> injector.get(LoginService); 
    backend = <MockBackend> injector.get(MockBackend); 
    authenticationService = <AuthenticationService> injector.get(AuthenticationService) 
    }); 

    afterEach(() => backend.verifyNoPendingRequests()); 

    it('should authenticate with the web api',() => { 
     let loginUrl = Constants.loginUrl; 
     let loginData:LoginModel = new LoginModel('username', 'password'); 

     backend.connections.subscribe((c: MockConnection) => { 
     expect(c.request.url).toEqual(loginUrl); 
     c.mockRespond(new Response(new ResponseOptions({ body: '{"token": "mockAuth"}' }))); 
     }); 

    //Correct login data 
    loginService.postLogin(loginData).subscribe((data) => {   
     expect(data.token).toBe('mockAuth'); 
    }); 

    }); 

また、どのように行いますあなたはテストを実行するときにデバッグしますか? console.logは動作しておらず、デバッガも動作していません。

答えて

0

申し訳ありませんが、問題は、直接すべてを実行するのではなく、.mapセクションのメソッドを呼び出すようだったようです。

ソリューション:

削除authsuccess

.map((response) => { 
     this.isAuthenticated = true; 
     this.authenticationService.saveToken(response.json().token); 
     return response.json(); 
}) 
関連する問題