Сбой кармы: Uncaught (в обещании): NullInjectorError: StaticInjectorError (DynamicTestModule) [RouterLinkWithHref -> LocationStrategy]: - PullRequest
0 голосов
/ 29 сентября 2019

Я новичок в angular и пытаюсь подготовить тестовый блок для моего компонента входа в систему.Я добавил маршрутизатор в свой провайдер, но тест не пройден.Попытался добавить RouterTestingModule, но он выдает TypeError: Cannot read property 'subscribe' of undefined

Тест кармы

LoginComponent > form invalid when empty
NullInjectorError: StaticInjectorError(DynamicTestModule)[RouterLinkWithHref -> LocationStrategy]: 
  StaticInjectorError(Platform: core)[RouterLinkWithHref -> LocationStrategy]: 
    NullInjectorError: No provider for LocationStrategy!
error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'RouterLinkWithHref', Function ], ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 17714755, rootNodeFlags: 1, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 1, childFlags: 17714755, directChildFlags: 1, childMatchedQueries: 0, matchedQueries: Object({  }), matchedQueryIds: 0, references: Object({  }), ngContentIndex: null, childCount: 65, bindings: [  ], bindingFlags: 0, outputs: [  ], element: Object({ ns: '', name: 'div', attrs: [ Array ], template: null, componentProvider: null, componentView: null, componentRendererType: null, publicProviders: null({  }), allProviders: null({  }), handleEvent: Function }), provider: null, text: null, query: null, ngContent: null }), Object({ nodeIndex: 1, parent: Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0,  ...
    at <Jasmine>
    at NullInjector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:1354:1)
    at resolveToken (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:1681:1)
    at tryResolveToken (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:1607:1)
    at StaticInjector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:1470:1)
    at resolveToken (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:1681:1)
    at tryResolveToken (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:1607:1)
    at StaticInjector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:1470:1)
    at resolveNgModuleDep (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:23118:1)
    at NgModuleRef_.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:24206:1)
    at resolveDep (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:24736:1)

LoginComponent.ts

import { ActivatedRoute, Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { AuthenticationService } from '@/_services';
import { first } from 'rxjs/operators';
import { AuthentService } from '@/shared/_services/authentication/authentication.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
@Component({ templateUrl: 'login.component.html' })
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  loading = false;
  submitted = false;
  returnUrl: string;
  error = '';

  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private authent: AuthentService,
    private authenticationService: AuthenticationService
  ) {
    // redirect to home if already logged in
    if (this.authenticationService.currentUserValue) {
      // this.router.navigate(['/']);
    }
  }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });

    // get return url from route parameters or default to '/'
    // this.returnUrl = this.route.snapshot.queryParams.returnUrl || '/';
  }


  get f() {
    return this.loginForm.controls;
  }

  onSubmit() {
    this.submitted =true;
    if (this.loginForm.invalid) {
      return;
    }
    const data = Object.assign({}, this.loginForm.value);
    this.authenticationService.login(data).pipe(first()).subscribe(data => {
      this.authenticationService.redirectPage();
    });
  }
}

LoginComponent.spec.ts

import { ActivatedRoute, Router } from '@angular/router';
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AuthentService } from '@/shared/_services/authentication/authentication.service';
import { AuthenticationService } from './../../_services/authentication.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { LoginComponent } from './login.component';
import { RouterTestingModule } from '@angular/router/testing';
import { SharedModule } from '../../shared/shared.module';

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  const fakeActivatedRoute = {
    snapshot: {
      queryParams: {
        returnUrl: '/'
      }
    }
  };
  const routerSpy = jasmine.createSpyObj('Router', ['navigate']);

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        FormsModule,
        HttpClientTestingModule,
        SharedModule,
        RouterTestingModule
      ],
      declarations: [LoginComponent],
      providers: [
        { provide: Router, useValue: routerSpy },
        { provide: ActivatedRoute, useFactory: () => fakeActivatedRoute },
        AuthentService,
        AuthenticationService
      ]
    }).compileComponents();
  }));

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

  it('form invalid when empty', () => {
    expect(component.loginForm.valid).toBe(false);
  });

  it('username field validity', () => {
    const email = component.loginForm.controls.email;
    expect(email.valid).toBe(false);

    email.setValue('');
    expect(email.hasError('required')).toBeTruthy();
  });

  it('password field validity', () => {
    const password = component.loginForm.controls.password;
    expect(password.valid).toBeFalsy();

    password.setValue('');
    expect(password.hasError('required')).toBeTruthy();
  });
});

Редактировать: Обновлены спецификации после импорта службы аутентификации и аутентификации

TypeError: Cannot read property 'subscribe' of undefined
error properties: Object({ ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 17714755, rootNodeFlags: 1, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 1, childFlags: 17714755, directChildFlags: 1, childMatchedQueries: 0, matchedQueries: Object({  }), matchedQueryIds: 0, references: Object({  }), ngContentIndex: null, childCount: 65, bindings: [  ], bindingFlags: 0, outputs: [  ], element: Object({ ns: '', name: 'div', attrs: [ Array ], template: null, componentProvider: null, componentView: null, componentRendererType: null, publicProviders: null({  }), allProviders: null({  }), handleEvent: Function }), provider: null, text: null, query: null, ngContent: null }), Object({ nodeIndex: 1, parent: Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 1, childFlags: 17714755, directChildFlags: 1, chi ...
    at <Jasmine>
    at new RouterLinkWithHref (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/router/fesm2015/router.js:6664:1)
    at createClass (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:24584:1)
    at createDirectiveInstance (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:24400:1)
    at createViewNodes (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:35006:1)
    at callViewAction (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:35456:1)
    at execComponentViewsAction (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:35361:1)
    at createViewNodes (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:35035:1)
    at createRootView (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:34878:1)
    at callWithDebugContext (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:36407:1)
    at Object.debugCreateRootView [as createRootView] (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:356

1 Ответ

2 голосов
/ 29 сентября 2019

Вы должны добавить RouterTestingModule и удалить строки ниже:

{ provide: Router, useValue: routerSpy },
{ provide: ActivatedRoute, useFactory: () => fakeActivatedRoute },
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...