Angular单元测试TypeError:无法读取undefined的属性'subscribe'

时间:2018-03-19 00:42:46

标签: angular unit-testing

我已在我的组件ngOnInit

中添加了此代码
  ngOnInit(): void {
    this.auth.user.subscribe((user) => {
      this.getById(user.id);
    });
  }

一切正常,但现在我的单元测试开始失败并出现错误TypeError: Cannot read property 'subscribe' of undefined

我已经看过这个问题https://github.com/angular/angular/issues/10127,但没有任何帮助。

任何想法如何解决?

这是授权码:

@Injectable()
export class AuthService {

  user: Observable<User>;
  constructor(private http: HttpClient) { }

  //...

  public login(username, password): Observable<any> {
    return this.http.post<any>('api/auth', {username: username, password: password})
    .pipe(
      tap((user: User) => this.setAccessToken(JSON.stringify(user.accessToken))),
      tap((user: User) => this.user = Observable.of(user)),
      catchError((err, caught) => {
        return Observable.of(err);
      })
    );
  }

  public logout(): void {
    this.removeAccessToken();
    location.reload(true);
  }
}

单元测试看起来像:

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        RouterTestingModule,
        ReactiveFormsModule,
      ],
      declarations: [ UserComponent ],
      providers: [
        UserService
      ],
      schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA],
    })
    .compileComponents();
  }));

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

0 个答案:

没有答案