【问题标题】:Argument of type MockAuthService is not compatible with AuthService in AngularMockAuthService 类型的参数与 Angular 中的 AuthService 不兼容
【发布时间】:2018-05-24 11:54:05
【问题描述】:

身份验证服务

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);
}}

在为这个组件编写测试用例时,我正在创建一个假的 Auth Service 类,如下所示。

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;
});});

我通过创建 Fake 类来使用 Mocking。(不是通过扩展或创建 Spy)

如何使我的 Fake 类(Mock)与真正的 Auth 类兼容。

谢谢。

【问题讨论】:

    标签: javascript angular jasmine mocking


    【解决方案1】:

    使用这样的扩展来获取 authService 的所有其他功能,您可以覆盖您需要的方法

    class MockAuthService extends AuthService {}
    

    【讨论】:

      猜你喜欢
      • 2018-09-07
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      • 2021-03-08
      • 2012-11-06
      • 2019-07-11
      相关资源
      最近更新 更多