gpt4 book ai didi

angular - Jasmine 测试属性可观察订阅

转载 作者:行者123 更新时间:2023-11-28 20:35:52 26 4
gpt4 key购买 nike

我有这个代码:

export class ProgramComponent implements OnInit {
@Input() events: Observable<any>;
eventsSubscription: any;
...
ngOnInit() {
this.eventsSubscription = this.events.subscribe((event) => {
... <- Some code that I want to test!!!!
console.log("The test doesn't get past here!!!!");
});
}
}

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

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
...
],
declarations: [ProgramComponent],
providers: [
...
]
}).compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(ProgramComponent);
component = fixture.componentInstance;

// HERE I WANT TO SPY ON THAT EVENTS OBSERVABLE AND RETURN SOME VALUE
// I tried this without success
spyOn(component, 'events').and.returnValue({type: 'somevalue'}))

fixture.detectChanges();
});

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

问题是 fixture.detectChanges();不会触发可观察事件的订阅。我必须使用 spyOnProperty 吗?但它是组件的输入...

我已经检查了 thisthis .

谢谢!

最佳答案

是的,您必须使用 spyOnProperty因为它是您试图监视的属性(property)。但是,即使它不是一个属性,您的 spy 也不会返回其工作所需的预期类型。你的 spy 的返回值只是一个普通对象 { type: 'somevalue' } ,但是 events属性需要一个 Observable<any> 类型的值.当组件尝试调用 subscribe 时,这很可能会导致错误。在 events 上属性,但普通对象不提供该方法。

对于这个测试用例,我只是简单地提供一个模拟 Observable并测试它发出的值是否已在您的组件中成功接收(我假设您将从 Observable 接收的任何内容分配给组件中的某个属性)。

这看起来像这样:

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

it('should test the component', () => {
// provide an Observable with whatever value you need in your component
component.events = of({type: 'somevalue'});

// nothing happened yet
expect(component.eventsSubscription).toBeFalsy();
expect(component.valueReceived).toBeUndefined();

// this should trigger change detection and your ngOnInit
fixture.detectChanges();

// verify whatever you need
expect(component.eventsSubscription).toBeTruthy();
expect(component.valueReceived).toEqual({type: 'somevalue'});
});

在你的组件中:

@Input() events: Observable<any>;
eventsSubscription: any;
valueReceived: any;

ngOnInit() {
this.eventsSubscription = this.events.subscribe((event) => {
this.valueReceived = event;
console.log("The test doesn't get past here!!!!");
});
}

关于angular - Jasmine 测试属性可观察订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54461169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com