Ошибка: ожидаемая шпионская навигация была вызвана с помощью: [['/ client / register']], но никогда не вызывалась - PullRequest
0 голосов
/ 25 апреля 2020

Ошибка Ожидается, что шпионская навигация была вызвана с: [['/ client / register']], но никогда не вызывалась. Это ошибка, которую я получаю. Кроме того, я не знаю, как проверить значение повара ie, так как это пакет на вечеринку. Я попробовал эту ссылку Ожидается, что шпионская навигация была вызвана с [['users']], но она никогда не вызывалась в интеграционном тестировании angular CLI , но она не работает для меня.

Registration.component.spe c .ts

import { RegisterComponent } from './../register/register.component';
import { MockAuthService } from './../../../mock/mockAuth.service';
import { AuthService } from './../../../services/auth/auth.service';
import { HttpClient } from '@angular/common/http';
import { MockProjectService } from './../../../mock/mockProject.service';
import { MustMatchDirective } from './../../../directive/must-match.directive';
import { FormsModule } from '@angular/forms';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { SignupComponent } from './signup.component';
import { RouterTestingModule } from '@angular/router/testing';
import { Router } from '@angular/router';

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

  let service:MockAuthService;

  let mockRouter 
  beforeEach(async(() => {
    mockRouter = { navigate: jasmine.createSpy('navigate') };
    TestBed.configureTestingModule({
      declarations: [ RegisterComponent, SignupComponent, MustMatchDirective],
      imports: [

        RouterTestingModule.withRoutes([
          { path: 'client/register', component: RegisterComponent }
      ]),
        FormsModule

    ],
    providers: [
      {
        provide: AuthService,
        useClass: MockAuthService
      },
      { provide: Router, useValue: mockRouter},
    ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SignupComponent);
    component = fixture.componentInstance;

    service = TestBed.get(AuthService);

    fixture.detectChanges();
  });

  it('should navigate to register pgae when server return success message', () => {

    component.onSubmit();

    expect(mockRouter.navigate).toHaveBeenCalledWith(['/client/register']); 

  })


});

Registration.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { AuthService } from './../../../services/auth/auth.service';


@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.scss']
})
export class SignupComponent implements OnInit {

  model: any = {};

  constructor(public router: Router, private cookieService: CookieService, private authService: AuthService) { }

  ngOnInit(): void { }

  onSubmit() {

    this.authService.signup(this.model).subscribe((response)=>{ 
      this.cookieService.set( 'token', response['token'],1 );
      console.log(response)

      this.router.navigate['/client/register'];
     })

  }

}

1 Ответ

0 голосов
/ 28 апреля 2020

это асинхронный код, который вы пытаетесь протестировать, поэтому попробуйте asyn c и whenStable , что-то вроде этого:

it('should navigate to register pgae when server return success message', async(() => {
 component.onSubmit();
 fixture.whenStable().then(() => {
   fixture.detectChanges();
   expect(mockRouter.navigate).toHaveBeenCalledWith(['/client/register']); 
 });
}));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...