this.notification.Success ошибка в угловом проекте - PullRequest
0 голосов
/ 08 мая 2019

Здравствуйте. Я выполняю тестирование на угловое, но получаю ошибку в тестовом примере, так как не могу найти решение этой проблемы. Это в основном проблема с уведомлением, так как я не понимаю, как определить Успех в моих тестовых примерах

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)

Ответы [ 2 ]

0 голосов
/ 08 мая 2019

Здравствуйте, я добавил провайдеров: [{обеспечить: ToasterService, useClass: ToasterService}, {предоставить: APP_BASE_HREF, useValue: '/'}], но не работает, так как я получаю еще одну ошибку для всех тестовых случаев

Сбой: Uncaught (в обещании): ReferenceError: toastr не определен ReferenceError: toastr не определен в ToasterService.setting (webpack: ///./src/app/services/toaster.service.ts?: 27: 9) в новом ToasterService (веб-пакет: ///./src/app/services/toaster.service.ts?: 15: 14)

0 голосов
/ 08 мая 2019

Проблема в строке ниже -

providers: [{provide:ToasterService,useValue:true}, { provide: APP_BASE_HREF, useValue: '/' }],

Замените useValue на useClass, как показано ниже ...

providers: [{provide: ToasterService, useClass: ToasterService}, {provide: APP_BASE_HREF, useValue: '/'}]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...