问题通常是由于Observable的内部状态没有正确重置所导致的。为了解决这个问题,可以使用jasmine的beforeEach
钩子,在每个测试之前重置Observable的内部状态。
示例代码:
import { of } from 'rxjs';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
}).compileComponents();
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
it('should call getData() twice and return correct values', () => {
// mock the observable
spyOn(component.myService, 'getData').and.returnValue(
of([{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }])
);
// first call
component.getData();
expect(component.data).toEqual([{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]);
// reset the internal state of the observable
spyOn(component.myService, 'getData').and.returnValue(
of([{ id: 3, name: 'Bob' }, { id: 4, name: 'Alice' }])
);
// second call
component.getData();
expect(component.data).toEqual([{ id: 3, name: 'Bob' }, { id: 4, name: 'Alice' }]);
});
});
在这个示例中,beforeEach
钩子会在每个测试运行之前创建组件和测试环境。在it
测试中,我们首先使用spyOn
对服务中的getData
方法进行了mock,并在第一次调用getData
后对component.data
的值进行了断言。然后,我们使用相同的方法重置了getData
,并在第二次调用getData
后对component.data
的