【问题标题】:How do I test a component that subscribes to a service?如何测试订阅服务的组件?
【发布时间】:2020-01-07 20:46:56
【问题描述】:

我对 Angular 中的单元测试比较陌生。我正在使用 Jasmine,但我发现 API 含糊不清。我正在尝试为我的组件编写良好的测试,但我在如何测试订阅服务数据的组件上陷入困境。

// 组件

ngOnInit() {
    this.store.dispatch(this.loadDatagridDataAction({data: this.authorizations}));

    this.authorizationService.initAuthorizations();
    this.authorizationService.authorizations.subscribe(authorizations => {
        this.realAuthorizations = authorizations;
        this.realAuthorizations.results.forEach(authorization => {

            const formatAuthorization = {};

            if (authorization.number) {
                formatAuthorization['number'] = authorization.number;
            }

            if (authorization.status) {
                formatAuthorization['status'] = authorization.status;

            }

            if (authorization.requesting_provider) {
                const requestingProvider = flattenObject(authorization.requesting_provider);
                formatAuthorization['requesting_provider'] = requestingProvider['name'];

            }

            if (authorization.servicing_provider) {
                const servicingProvider = flattenObject(authorization.servicing_provider);
                formatAuthorization['servicing_provider'] = servicingProvider['name'];

            }

            if (authorization.termination_date) {
                formatAuthorization['termination_date'] = authorization.termination_date;
            }

            this.formattedAuthorizations.push(formatAuthorization);
        });

    });

}

setActiveTab(tab) {
    this.store.dispatch(this.setActiveTabAction({tab}));
}

setActiveRow(row) {
    console.log(row);
}

setCurrentPage(page) {
    this.store.dispatch(this.setPaginatorCurrentPageAction({page}));
}

goBack(route) {
    console.log(route);
}

}

// 服务

export class AuthorizationService {

private _authorizations = new Subject<any>();

constructor(
    private http: HttpClient,
) { }

public get authorizations() {
    return this._authorizations.asObservable();
}

public getAuthorizations() {
    const auth = '/api/enrollment/tocs/';
    return this.http.get(auth);
}

public initAuthorizations() {
    this.getAuthorizations().subscribe(data => {
        this._authorizations.next(data);
    }, error => {
        console.log('Failed to get data', error);
    });
}

}

// 单元测试

describe('AuthorizationsReferralsComponent', () => {
let component: AuthorizationsReferralsComponent;
let fixture: ComponentFixture<AuthorizationsReferralsComponent>;
let storeMock;
let configurationServiceMock;
let authorizationMockService;

beforeEach(async(() => {
    storeMock = {
        select: jasmine.createSpy('select'),
        dispatch: jasmine.createSpy('dispatch'),
    };

    authorizationMockService = jasmine.createSpyObj(['getAuthorizations', 'initAuthorizations', 'authorizations']);

    configurationServiceMock = {
        getTemplateConfiguration: () => {}
    };

    TestBed.configureTestingModule({
        declarations: [ AuthorizationsReferralsComponent ],
        imports: [SidebarTableViewModule,  HttpClientTestingModule],
        providers: [
            {
                provide: Store,
                useValue: storeMock
            },
            {
                provide: ConfigurationService,
                useValue: configurationServiceMock,
            },
            {
                provide: AuthorizationService,
                useValue: authorizationMockService
            },

        ]
    })
    .compileComponents();
}));

beforeEach(() => {
    HEROES = [
      {id: 1, name: 'SpiderDude', strength: 8},
      {id: 2, name: 'Wonderful Woman', strength: 24},
      {id: 3, name: 'SuperDude', strength: 55}
    ];

    fixture = TestBed.createComponent(AuthorizationsReferralsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

it('should create', () => {
    authorizationMockService.initAuthorizations.and.returnValue(of(HEROES));
    fixture.detectChanges();

    expect(fixture.componentInstance.realAuthorizations.length).toBe(3);
});

});

我收到以下错误TypeError: this.authorizationService.authorizations.subscribe is not a function

它似乎认为我的get authorizations() 函数不是函数。如何适当地模拟我的服务,以便测试订阅中的语句?

 this.authorizationService.authorizations.subscribe(

【问题讨论】:

  • 如果从get authorizations() 中删除get 会发生什么?
  • 我的功能不起作用,测试没有运行
  • 查看article

标签: angular unit-testing jasmine observable


【解决方案1】:

现在你的模拟服务没有返回任何东西,你的组件期望它返回一个 Observable。

在您的测试中,您需要以下行:

authorizationMockService.authorizations.and.returnValue(of([])

请注意,上面的内容使它返回一个带有空数组的 Observable。如果要返回实际数据,则需要进行设置。

【讨论】:

  • 仔细查看您的测试,您可能想要 and.returnValue(of[HEROES]) 而不是空数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
  • 1970-01-01
  • 2019-09-25
  • 2019-02-13
相关资源
最近更新 更多