您好,我正在测试角度,但由于无法找到解决此问题的方法,因此在测试用例中出现错误。 这基本上是一个通知问题,因为我不了解如何在测试用例中定义成功
login.component.spec.ts
import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { DebugElement } from '@angular/core';
import { FormsModule, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { LoginComponent } from './login.component';
import { By, BrowserModule } from '@angular/platform-browser';
import { NgxLoadingModule } from 'ngx-loading';
import { RouterModule } from '@angular/router';
import { routes } from '../../app.routing';
import { RouterTestingModule } from '@angular/router/testing';
import { P404Component } from '../../views/error/404.component';
import { P500Component } from '../../views/error/500.component';
import { RegisterComponent } from '../register/register.component';
import { ForgotPasswordComponent } from '../forgot-password/forgot-password/forgot-password.component';
import { ResetpasswordComponent } from '../resetpassword/resetpassword.component';
import { ChangepasswordComponent } from '../changepassword/changepassword.component';
import { DefaultLayoutComponent } from '../../containers/default-layout/default-layout.component';
import {
AppAsideModule,
AppBreadcrumbModule,
AppHeaderModule,
AppFooterModule,
AppSidebarModule,
} from '@coreui/angular';
// import { LocalStorageService } from 'angular-2-local-storage';
import { PerfectScrollbarModule } from 'ngx-perfect-scrollbar';
import { APP_BASE_HREF } from '@angular/common';
import { HttpClientModule, HttpClient } from '@angular/common/http';
// import { Router, RouterOutlet } from '@angular/router';
import { ToasterService } from '../../services/toaster.service';
// import {RouterModule} from '@angular/router';
// import { Observable } from 'RxJs';
fdescribe('LoginComponent', () => {
let notification: ToasterService = null;
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let de: DebugElement;
let el: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [LoginComponent, RegisterComponent, ForgotPasswordComponent, ResetpasswordComponent,
ChangepasswordComponent, DefaultLayoutComponent, P404Component, P500Component],
imports: [
HttpClientModule,
RouterModule.forRoot(routes),
RouterTestingModule.withRoutes([]),
FormsModule,
BrowserModule,
NgxLoadingModule,
ReactiveFormsModule,
AppAsideModule,
AppBreadcrumbModule,
AppHeaderModule,
AppFooterModule,
AppSidebarModule,
PerfectScrollbarModule,
],
providers: [{provide:ToasterService,useValue:true}, { provide: APP_BASE_HREF, useValue: '/' }],
})
.compileComponents().then(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
de = fixture.debugElement.query(By.css('form'));
});
}));
// beforeEach(inject([ToasterService], (userService: ToasterService) => {
// notification = userService;
// }));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
// test cases
fit('should create', () => {
expect(component).toBeTruthy();
});
fit('should render the title ',()=>{
fixture=TestBed.createComponent(LoginComponent);
fixture.detectChanges();
const compiled=fixture.debugElement.nativeElement;
expect(compiled.querySelector('h2').textContent).toContain('Sign up');
});
fit('should render the title Welcome to API Mining ',()=>{
fixture=TestBed.createComponent(LoginComponent);
fixture.detectChanges();
const compiled=fixture.debugElement.nativeElement;
expect(compiled.querySelector('p.well').textContent).toContain('Welcome to API Mining ! ');
});
fit('should render the title login',()=>{
fixture=TestBed.createComponent(LoginComponent);
fixture.detectChanges();
const compiled=fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Login');
});
fit('should render the title Sign In to your account',()=>{
fixture=TestBed.createComponent(LoginComponent);
fixture.detectChanges();
const compiled=fixture.debugElement.nativeElement;
expect(compiled.querySelector('p').textContent).toContain('Sign In to your account');
});
fit('should call login method',()=>{
fixture=TestBed.createComponent(LoginComponent);
fixture.detectChanges();
var val={
'username':'icici',
'password':'1234'
}
component.login(val);
expect(component.submitted).toBeTruthy();
});
login.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
// import { LoginService } from 'app/main/login/logindetails.service';
import { Http, Response, Headers } from '@angular/http';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
// import { ToasterService } from '../service/toaster.service';
import { HttpClient, HttpParams, HttpRequest, HttpEvent } from '@angular/common/http';
import { ToasterService } from '../../services/toaster.service';
// ----------------- map -----------------------
import 'rxjs/add/operator/map';
import { map } from 'rxjs/operators';
import 'rxjs/Rx';
import { Observable } from 'rxjs';
import 'rxjs/add/observable/throw';
@Component({
selector: 'app-dashboard',
templateUrl: 'login.component.html'
})
export class LoginComponent {
//loader
public loading: boolean = false;
public submitted:boolean;
loginForm: FormGroup;
loginData: any[];
authenticateObj = {};
info;
companyName;
checkUser;
//localStorage
individualFilesName;
individualFilesPath;
constructor(
private _formBuilder: FormBuilder,
private router: Router,
// private _loginService:LoginService,
private fb: FormBuilder,
private http: HttpClient,
private notification: ToasterService,
) { }
ngOnInit(): void {
// localStorage.clear();
//clear localStorage -
localStorage.removeItem("token");
localStorage.removeItem("username")
localStorage.removeItem('sets');
this.individualFilesName = localStorage.getItem("companyName") + "allFiles"; //put in clear database;
this.individualFilesPath = localStorage.getItem("companyName") + "allFilesPath"; //put in clear database;
console.log("inside login, localStorage.getItem(this.individualFilesName ) = ", JSON.parse(localStorage.getItem(this.individualFilesName)));
console.log("inside login, localStorage.getItem(this.individualFilesPath ) = ", JSON.parse(localStorage.getItem(this.individualFilesPath)))
console.log("************** Login Init Ends *************************");
this.loginForm = this._formBuilder.group({
username: ['', [Validators.required]],
password: ['', Validators.required]
});
}
logindemo():void{
this.submitted=true;
}
login(data) {
console.log("Inside Login");
this.submitted=true;
this.authenticateObj = {
username: data.username,
password: data.password
}
this.loading = true;
// When login page not required.
if (data.username == "icici" && data.password == "1234") {
this.loading = false;
this.notification.Success('Login Successful');
localStorage.setItem("username", "cateina");
this.router.navigate(['/file-upload/wsdl']);
} else {
this.loading = false;
this.notification.Error('Login Failed. Username or Password is incorrect');
}
}
toaster.service.ts
import { Injectable } from '@angular/core';
declare var toastr:any;
@Injectable()
export class ToasterService {
constructor() {
this.setting();
}
Info(title:string)
{
toastr.info(title);
}
Success(title:string)
{
toastr.success(title);
}
Error(title:string){
toastr.error(title);
}
setting()
{
toastr.options = {
"closeButton": false,
"debug": false,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-top-right",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "1800",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
}
}
我想删除此错误但得到
TypeError: this.notification.Success is not a function
at <Jasmine>
at LoginComponent.login (webpack:///./src/app/views/login/login.component.ts?:65:31)
at UserContext.eval (webpack:///./src/app/views/login/login.component.spec.ts?:103:19)
at ZoneDelegate.invoke (webpack:///./node_modules/zone.js/dist/zone.js?:390:26)
at ProxyZoneSpec.onInvoke (webpack:///./node_modules/zone.js/dist/zone-testing.js?:288:39)
at ZoneDelegate.invoke (webpack:///./node_modules/zone.js/dist/zone.js?:389:52)
at Zone.run (webpack:///./node_modules/zone.js/dist/zone.js?:149:43)
at runInTestZone (webpack:///./node_modules/zone.js/dist/zone-testing.js?:509:34)
at UserContext.eval (webpack:///./node_modules/zone.js/dist/zone-testing.js?:524:20)
答案 0 :(得分:0)
问题在下面的行中-
providers: [{provide:ToasterService,useValue:true}, { provide: APP_BASE_HREF, useValue: '/' }],
将useValue替换为useClass,如下所示...
providers: [{provide: ToasterService, useClass: ToasterService}, {provide: APP_BASE_HREF, useValue: '/'}]
答案 1 :(得分:0)
您好,我确实添加了提供程序:[{提供:ToasterService,useClass:ToasterService},{提供:APP_BASE_HREF,useValue:'/'}] 但无法正常工作,因为我现在所有测试用例都出现另一个错误
失败:未捕获(按承诺):ReferenceError:未定义Toastr ReferenceError:未定义烤面包机 在ToasterService.setting(webpack:///./src/app/services/toaster.service.ts?:27:9) 在新的ToasterService(webpack:///..src/app/services/toaster.service.ts?:15:14)