import { Component, Input, OnInit } from '@angular/core';
import {DataplansDetails} from '../../models/dataplans-details';
import * as _ from "lodash";
@Component({
selector: 'jsonform',
templateUrl: './jsonform.component.html',
styleUrls: ['./jsonform.component.scss']
})
export class JsonformComponent implements OnInit {
@Input() dataplanDetails: any;
public layout: any = [];
public schema: any = {};
ngOnInit() {
this.dataplanDetails.subscribe(res => {
const fileSchema = JSON.parse(res.details.submissionFileSchema)
const formLayout = fileSchema["layout"]
this.schema = {
type: "object",
properties: fileSchema["properties"]
}
const schemaKeys = Object.keys(this.schema["properties"])
这是我的组件。它有subscribe
,我在单元测试时遇到问题。我的测试包括:
fdescribe('JsonformComponent', () => {
let component: JsonformComponent;
let fixture: ComponentFixture<JsonformComponent>;
const mockObservable = new Subject();
beforeEach(async(() => {
TestBed.configureTestingModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
providers: [
{provide: Store, useClass: StoreStub}
],
imports: [],
declarations: [JsonformComponent]
}).compileComponents();
}));
beforeEach(async(() => {
fixture = TestBed.createComponent(JsonformComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component['dataplanDetals'] = mockObservable
}));
it('should create', () => {
expect(component).toBeTruthy();
});
fit('should not set layout if there are no properties', () => {
mockObservable.next({test: 'data'})
component.parseSchema('{"layout": [], "properties": {}}')
// component.properties = false
expect(component.schema).toEqual({})
expect(component.layout).toEqual([])
})
// it('should set the layout to have the keys', () => {
// component.properties = {}
// })
});
我收到错误:Failed: undefined is not an object (evaluating 'this.dataplanDetails.subscribe')
如何从测试中触发订阅?
答案 0 :(得分:2)
1)将subscribe
回调拉入其自己的方法并直接测试。
2)模拟dataplanDetails
的发射。例如:
const mockObservable = new Subject();
component['dataplanDetails'] = mockObservable;
mockObservable.next({ test: 'data' });
...now you should hit the `subscribe` block
答案 1 :(得分:0)
Angular 2 RC5 Testing Promises in ngOnInit Not Working
我想测试定义订阅是否足够,或者你可能会触发loadingObservable将isLoading切换为true或false。
如果您正在使用 loadingObservable ,请尝试切换为 isLoading 并将其设置为true / false