Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

angular - karma TypeError "Cannot read property 'subscribe' of undefined"

While testing a simple component that has a shared service, the following error message appears, and I cannot manage to make it work, I've tried everything!

TypeError: Cannot read property 'subscribe' of undefined

lr.component.ts

export class LrComponent implements OnDestroy {
  currentRouter: string;
  private subscription: Subscription;

  constructor(private lrService: LrService) {
    this.subscription = this.lrService.lrNavigation$.subscribe(
      (currentNav: string) => {
        this.currentRouter = currentNav;
      },
      (error) => {
        console.warn(error);
      }
    );
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

lr.service.ts

@Injectable()
export class LrService {
  // Observables for our components to subscribe to.
  lrNavigation$: Observable<string>;

  // Subjects to return data to subscribed components
  private lrNavigationSubject = new Subject<string>();

  constructor() {
    this.lrNavigation$ = this.lrNavigationSubject.asObservable();
  }

  // Triggers subscribed components
  lrNavigate(currentNav: string) {
    this.lrNavigationSubject.next(currentNav);
  }
}

any-random.component.ts

// In another component we send the string that we want the subscribed component (LrComponent) to receieve
this.lrService.lrNavigate('LR');

lr.component.spec.ts

class MockRouter {
  navigate = jasmine.createSpy('navigate');
}

class MockActivatedRoute {
  params = jasmine.createSpy('params');
}

class MockLrService extends LrService {
  lrNavigation$: Observable<string> = new Subject<string>().asObservable();

  constructor() {
    super();
  }

  lrNavigate(currentRouter: string) {
    return Observable.of(['LR']);
  }
}

export function main() {
  describe('LrComponent', () => {
    let fixture: ComponentFixture<LrComponent>;
    let component: LrComponent;
    let lrService: LrService;

    beforeEach(async(() => {
      TestBed.configureTestingModule({
        declarations: [
          LrComponent,
          LrMappingsComponent,
          LrCategoriesComponent,
        ],
        imports: [
          RouterTestingModule,
          CommonModule,
          LrRoutingModule,
          SharedModule,
          AgGridModule.withComponents(
            [
              CaseSensitiveFilterComponent,
              ButtonComponent,
              ColumnHeaderComponent,
              TypeaheadEditorComponent,
              ButtonGroupComponent
            ]
          )
        ],
        providers: [
          { provide: LrService, useClass: MockLrService },
          { provide: Router, useClass: MockRouter },
          { provide: ActivatedRoute, useClass: MockActivatedRoute },
        ]
      }).compileComponents();
    }));

    beforeEach(() => {
      fixture = TestBed.createComponent(LrComponent);
      component = fixture.componentInstance;
      lrService = fixture.debugElement.injector.get(LrService);
    });

    it('should create LrComponent', () => {
      fixture.detectChanges();
      expect(component).toBeDefined();
    });

    it('should have the current router set', async(() => {
      fixture.detectChanges();
      expect(component.currentRouter).toEqual('LR', 'the data should be `LR`');
    }));
  });
}

ERROR

enter image description here

NOTE:

If I use ONLY Jasmine, with no Angular testing framework stuff, it works. But that's not how I want to test @Component's.

Example:

export function main() {
  describe('LrComponent', () => {
    let fixture: ComponentFixture<LrComponent>;
    let component: LrComponent;
    let lrService: LrService;

    beforeEach(() => {
      lrService = new MockLrService();
      component = new LrComponent(lrService);
    });

    it('should create LrComponent', () => {
      fixture.detectChanges();
      expect(component).toBeDefined();
    });
  });
}

This works, but is not what I want.

Any clue on how to solve this issue? I really tried many things and none worked...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok, I'll answer myself in case someone faces the same issue.

Turns out that deleting:

{ provide: Router, useClass: MockRouter }

Solved the issue. I really don't know why. I was convinced it was some issue with the Observables from the service...

These dependencies were here because of this:

it('should be able to navigate through tabs',
      fakeAsync((inject([Router, Location], (router: Router, location: Location) => {
        router.initialNavigation();

        let tabLinks, a1, a2;
        fixture.detectChanges();

        tabLinks = fixture.debugElement.queryAll(By.css('a.mappings'));
        a1 = tabLinks[0];
        a2 = tabLinks[1];


        a1.triggerEventHandler('click', { button: 0 });
        tick();
        expect(location.path()).toEqual('lrMappings');

        a2.nativeElement.click();
        tick();
        expect(location.path()).toEqual('categories');
      }))));

But, removing them from providers and injecting them like shown here makes it work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...