如何解决如何在Jasmine / Angular中模拟服务的事件发射器
我正在尝试为具有依赖服务(包含EventEmitter)的组件编写单元测试。 我已在此组件中订阅了此事件发射器。 我该如何嘲笑?
相关服务:
flutter build apk -t lib/flavors/company_a/prod.dart --flavor=company_a_prod release --obfuscate --split-debug-info=obfuscate/symbols
组件具有功能:
Service A {
testEmitter : EventEmitter<any>();
}
如何模拟此订阅?该函数在初始化期间被调用,因此测试无法正常工作
解决方法
@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();
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。