-1

我一直在测试我的登录模块,但订阅没有得到测试,我也无法检查本地存储。到目前为止,我是初学者,我已经这样做了

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {MatSelectModule, MatInputModule, MatCardModule, MatButtonModule,MatDatepickerModule, MatNativeDateModule } from '@angular/material';
import { FormGroup, FormsModule, FormControl, FormBuilder, Validators,ReactiveFormsModule  } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import {HttpClientModule} from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 

import { LoginComponent } from './login.component';

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports: [ RouterTestingModule,ReactiveFormsModule , FormsModule ,MatSelectModule, HttpClientModule, MatInputModule, BrowserAnimationsModule, MatCardModule, MatButtonModule,MatDatepickerModule, MatNativeDateModule],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

这是测试覆盖率

在此处输入图像描述

login.component.ts -edit 添加登录组件

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormsModule, FormControl, FormBuilder, Validators } from '@angular/forms';
import { LoginService } from '../../services/login.service';
import { Router } from '@angular/router'
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginUserData = {}
loginForm: FormGroup;
constructor(private _login: LoginService, private _router: Router, private loginFormBuilder: FormBuilder) {
  this.createForm();
}
ngOnInit() {
}
createForm() {
  this.loginForm = this.loginFormBuilder.group({
    username: ['', Validators.required],
    password: ['', Validators.required]
  });
}
loginUser() {
    this._login.loginUser(this.loginUserData).subscribe(
      res => {
        localStorage.setItem('token', res.token)
        this._router.navigate(['/home'])
      },
      err => console.log(err))

  }

}

登录 html- 编辑添加的登录 html 页面

<mat-card class="login-main">
  <mat-card-title class="login-title">
    <span class="welcome">Welcome back</span>
    <img src="assets/logo.png" class="image-log" alt="logo">
  </mat-card-title>
  <mat-card-content class="login-content">
    <form [formGroup]="loginForm">
      <mat-form-field class="input-username">
        <input matInput formControlName="username" placeholder="Username" name="username" type="text" [(ngModel)]="loginUserData.username">
      </mat-form-field>
      <div *ngIf="loginForm.controls['username'].invalid && (loginForm.controls['username'].dirty || loginForm.controls['username'].touched)">
        <div class="error-text" *ngIf="loginForm.controls['username'].errors.required">
          Please enter the username.
        </div>
      </div>
      <mat-form-field class="input-password">
        <input matInput formControlName="password" placeholder="Password" name="password" type="password" [(ngModel)]="loginUserData.password">
      </mat-form-field>
      <div *ngIf="loginForm.controls['password'].invalid && (loginForm.controls['password'].dirty || loginForm.controls['password'].touched)">
        <div class="error-text" *ngIf="loginForm.controls['password'].errors.required">
          Please enter the password.
        </div>
      </div>
      <a routerLink="/forgotpassword" class="forgot-password">Forgot password?</a>
      
      <br>
      <button class="login-button" type="submit" (click)="loginUser()" [disabled]='loginForm.status =="INVALID"' mat-Button>LOGIN</button>
    </form>
  </mat-card-content>
</mat-card>

任何帮助,将不胜感激

谢谢

4

1 回答 1

0

你有一个loginService在你的类中调用的依赖项。在测试组件时,无需将实际服务添加到providers数组中。但是您必须提供模拟或存根服务作为登录服务。

首先像这样创建一个模拟服务对象。

const loginSuject = new Subject();

const mockLoginServce = {
   loginUser: () => {
     return loginSuject.asObservable();
   }
}

正如你在这里看到的,我从loginUser方法中返回了一个主题作为 Observerble。我们必须这样做,因为实际方法也返回一个Observable.

然后你必须将模拟服务添加到TestBedproviders 数组中。TestBed.get()并使用方法获取提供者实例。

 TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports: [], // your import go here.
      providers: [{provide: LoginService, useValue: mockLoginServce}]
    })
    .compileComponents();

 service = TestBed.get(LoginService);

当您测试组件的loginUser方法时,您应该调用subject.next(). 您可以将响应对象传递到next method.

你的测试服应该是这样的。

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MatSelectModule, MatInputModule, MatCardModule, MatButtonModule, MatDatepickerModule, MatNativeDateModule } from '@angular/material';
import { FormGroup, FormsModule, FormControl, FormBuilder, Validators, ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { LoginComponent } from './login.component';

import { Subject } from 'rxjs';

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let service: LoginService;

  const loginSuject = new Subject();

  const mockLoginServce = {
    loginUser: () => {
      return loginSuject.asObservable();
    }
  }

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [LoginComponent],
      imports: [RouterTestingModule, ReactiveFormsModule, FormsModule, MatSelectModule, HttpClientModule, MatInputModule, BrowserAnimationsModule, MatCardModule, MatButtonModule, MatDatepickerModule, MatNativeDateModule],
      providers: [{ provide: LoginService, useValue: mockLoginServce }]
    })
      .compileComponents();
    service = TestBed.get(LoginService);
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  describe('#loginUser tests', () => {
    it('Should return a valid response when loginService.loginUser is invoked', () => {
      const reponseData = { toke: 'asdasdasd' };
      loginSuject.next(reponseData);
      const loginUserData = {} // add the object here
      service.loginUser(loginUserData).subscribe((res) => {
        expect(res).toEqual(reponseData);
      });
    });
  });
});

您可以在 Angular官方文档中找到有关测试具有依赖性的 Angular 组件的更多信息

于 2018-07-03T07:48:53.313 回答