angular - Angular2 hur man mockar prenumererade parametrar från Activated Route


Jag har en komponent som får ett värde från params-egenskapen hos en ActivatedRoute.

Komponenterna ser ut så här:

......
  constructor(public userRegistration: UserRegistrationService, public userLogin: UserLoginService,
              public router: Router, public route: ActivatedRoute) {
  }

  ngOnInit() {
    this.verificationCode = new FormControl('', [Validators.required]);
    this.confirmationCodeForm = new FormGroup({verificationCode: this.verificationCode});

    //****************************** 
    this.sub = this.route.params.subscribe(params => {
      this.email = params['userId'];
    });
   //******************************
    this.errorMessage = null;
  }
 ......

Testen tillhandahåller en ActivatedRoute som "useValue" som mockar klassen. Testen ser ut så här:

describe('ConfirmRegistrationComponent', () => {
  let component: ConfirmRegistrationComponent;
  let fixture: ComponentFixture<ConfirmRegistrationComponent>;
  let userRegistrationService: UserRegistrationService;
  let userLoginService: UserLoginService;
  let router: Router;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule, RouterTestingModule, HttpClientModule],
      declarations: [ConfirmRegistrationComponent],
      providers: [UserRegistrationService, UserLoginService, {

        provide: ActivatedRoute,
        useValue: {'params': Observable.from([{userId: 1}])}

      }, ImageService, UserService, CognitoUtil,
        {
          provide: Router, useClass: class {
            navigate = jasmine.createSpy('navigate');
          }
        }]
    }).compileComponents();

    fixture = TestBed.createComponent(ConfirmRegistrationComponent);
    component = fixture.componentInstance;
    userRegistrationService = TestBed.get(UserRegistrationService);
    userLoginService = TestBed.get(UserLoginService);
    spyOn(userLoginService, 'isAuthenticated').and.callFake(function () {

    });
    router = TestBed.get(Router);
    fixture.detectChanges();
    component.ngOnInit();
  }));

  it('should create', () => {
  });
});

När jag kör testet får jag följande fel:

Failed: Cannot read property 'subscribe' of undefined
TypeError: Cannot read property 'subscribe' of undefined
    at new RouterLinkWithHref node_modules/@angular/router/esm5/router.js:6099:1)

Kan du hjälpa mig, snälla? Tack!

Svar #1

När du använder RouterTestingModule bör du inte lägga till en Router-leverantör i providers-samlingen (importera antingen RouterTestingModule eller tillhandahåll Router, men inte båda).

Dessutom vet jag inte om detta kommer att hjälpa, men jag hade ett relaterat problem i Angular 6 där jag var tvungen att använda denna syntax:

providers: [
    { provide: ActivatedRoute, useValue: {
            paramMap: of( convertToParamMap( { userId: 1 } ) )
        }
    }
],

convertToParamMap finns i @angular/Router

Svar #2

Lösningen som fungerade för mig var följande (Angular 7 + Jest):

const mockActivatedRoute = {
  snapshot: {
    paramMap: {
      get() { return '1'; }
    }
  }
};

Och använd det bara i leverantörer:

      providers: [
        { provide: ActivatedRoute, useValue: mockActivatedRoute },
      ],

Relaterade artiklar