【发布时间】: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