Аргумент типа MockAuthService не совместим с AuthService в Angular. - PullRequest
0 голосов
/ 24 мая 2018

Служба аутентификации

import { Injectable } from '@angular/core';
import {HttpClient } from '@angular/common/http';

@Injectable({
 providedIn: 'root'
})
export class AuthService {

constructor(private http : HttpClient) { }

public validateUser(email:string, password: string):boolean{
this.http.post("/api/user/validate",
{
    "email" : email,
    "password": password
});
return true;
}}

Компонент входа: -

import { Component, OnInit } from '@angular/core';
import {AuthService} from './../assets/services/auth.service';


@Component({
 selector: 'app-login',
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css']  
})

export class LoginComponent implements OnInit {

constructor(private authService:AuthService) { }

ngOnInit() {
}

public validateUser(email:string, password : string){
 this.authService.validateUser(email,password);
}}

При написании тестового примера для этого компонента я создаю поддельный класс службы аутентификации, как показано ниже.

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {HttpClient} from "@angular/common/http";
import { LoginComponent } from './login.component';

//Create a Fake class
 class MockAuthService {

/**
*tried with overloading constructor
*/
/*constructor(http:HttpClient) {

}*/
authenticated :boolean = false;

isUserValid() :boolean{
 return this.authenticated;
}}

describe('LoginComponent', () => {
 let component: LoginComponent;
 let service : MockAuthService;


 beforeEach(async(() => {
  service = new MockAuthService();
//This line is throwing compile time error 
//Arugument of type "MockAuthService" is not compatible to parameter of type "AuthService"
  component = new LoginComponent(service);

  }));

afterEach(() => {
  service = null;
  component = null;
});});

Я использую Mocking, создавая поддельный класс (не расширяя и не создавая Spy)

Как сделать мой поддельный класс (Mock) совместимым среальный Auth класс.

Спасибо.

1 Ответ

0 голосов
/ 24 мая 2018

use расширяет таким образом, чтобы получить все другие функции вашего authService, и вы можете переопределить нужные вам методы

class MockAuthService extends AuthService {}
...