Тестирование Angular Компонент, который подписывается на свойство publi c - PullRequest
0 голосов
/ 12 июля 2020

У меня есть компонент, который подписывается на свойство службы учетной записи: -

export class AppComponent {
    user: User;
    authenicated: boolean;

    constructor(private accountService: AccountService) {
        this.accountService.user.subscribe(x => this.user = x);
    }

    logout() {
        this.accountService.logout();
    }
}

Я хочу проверить это, но получаю Ошибка: this.accountService.user.subscribe не является функцией

Фрагмент сервиса Account: -

export class AccountService {
    private userSubject: BehaviorSubject<User>;
    **public user: Observable<User>;**

    constructor(
        private router: Router,
        private http: HttpClient
    ) {
        this.userSubject = new BehaviorSubject<User>(JSON.parse(sessionStorage.getItem('user')));
        this.user = this.userSubject.asObservable();
    }
 

Я могу без проблем использовать другие наблюдаемые типы в других тестовых классах, но не могу заставить это свойство работать. Теперь я пробовал издеваться, шпионить spyOnProperty, каждая из которых приводит к множеству разных ошибок

Мой пример

 const fakeUser: User ={
      id: 0,
        userName: 'TestUser',
        password: 'Password',
        firstName: 'Test',
        lastName: 'User',
        token: '',
        userType: {id: 1, type: 'god'},
        active: true,
        deleted: false,
        deletedDate: null,
        createdBy: 'mock',
        createdDate: new Date(),
        modifiedBy: '',
        modifiedDate: null
    }
    
    //const fakeAccountService =  jasmine.createSpyObj('accountService', [ 'login', 'user']);
    
    let mockAccountService =  {
      user:  () => of(fakeUser)
    };
    
    //spyOn(mockAccountService, 'user').and.returnValue(of(fakeUser));
    
    describe('AppComponent', () => {
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [AppComponent]
          , schemas: [NO_ERRORS_SCHEMA],
          providers: [{provide: AccountService, useValue: mockAccountService }]
        }).compileComponents();
      }));
    
      it('should create the app', async(() => {
        const fixture = TestBed.createComponent(AppComponent);
        const app = fixture.debugElement.componentInstance;
        expect(app).toBeTruthy();
      }));
...