sar*_*war 5 unit-testing mocking jasmine angular
我正在尝试为具有包含 EventEmitter 的依赖服务的组件编写单元测试。我已经在这个组件中订阅了这个事件发射器。我怎么能嘲笑这个呢?
相关服务:
Service A {
testEmitter : EventEmitter<any>();
}
Run Code Online (Sandbox Code Playgroud)
组件具有以下功能:
funcA() {
service.testEmitter.subscribe()....//
}
Run Code Online (Sandbox Code Playgroud)
我如何模拟此订阅?该函数在初始化期间被调用,因此测试将不起作用
@Injectable()
class SomeService {
testEmitter = new EventEmitter<any>();
}
@Component({
selector: 'app-some',
template: ''
})
class SomeComponent implements OnInit {
shouldCall = true;
constructor(private someService: SomeService) {
}
ngOnInit() {
if (this.shouldCall) {
this.funcA();
}
}
private funcA() {
this.someService.testEmitter.subscribe();
}
}
describe('SomeComponent', () => {
let component: SomeComponent;
let fixture: ComponentFixture<SomeComponent>;
let someServiceMock;
beforeEach(async(() => {
someServiceMock = {testEmitter: {subscribe: createSpy('testEmitter subscribe')}};
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [{provide: SomeService, useValue: someServiceMock}]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SomeComponent);
component = fixture.componentInstance;
// fixture.detectChanges(); // move to test suites as it cause ngOnInit call
});
it('should subscribe', () => {
fixture.detectChanges();
expect(someServiceMock.testEmitter.subscribe).toHaveBeenCalled();
});
it('should not subscribe', () => {
component.shouldCall = false;
fixture.detectChanges();
expect(someServiceMock.testEmitter.subscribe).toHaveBeenCalled();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10072 次 |
| 最近记录: |