I have a centralized DataStore to hold my report connections. So that I can manage report connections events like onShow, onError and onCancel; so the implementer doesn't have to. Anyways. How can I mock the SomeService.doSomething
function so that it returns my connection object and them emits on the onShow Subject. Please look at my should resolve test data
test. How can I mock this appropriately.
mockSomeService.doSomething.and.callFake(() => {
const response = new ReportManagerConnection();
response.onShow.next({ data: [ {id: 1} ]})
return response
})
Here is my test.
describe('SomeComponent', () => {
let component: SomeComponent;
let fixture: ComponentFixture<SomeComponent>;
beforeEach(async(() => {
const mockSomeService: jasmine.SpyObj<SomeService> = jasmine.createSpyObj<SomeService>(
'SomeService',
['doSomething']
);
mockSomeService.doSomething.and.callFake(() => {
const response = new ReportManagerConnection();
response.onShow.next({ data: [ {id: 1} ]})
return response
})
TestBed.configureTestingModule({
imports: [ ],
declarations: [SomeComponent],
providers: [
{ provide: SomeService, useValue: mockSomeService },
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should resolve test data', fakeAsync(() => {
component.loadData()
tick()
expect(component.data.length).toBeGreaterThan(0)
}));
});
Here is my code
export class ReportManagerConnection {
onShow: Subject<any>
onFinish: Subject<any>
onCancel: Subject<any>
onShow: Subject<any>
onStart: ReplaySubject<any>
onError: ReplaySubject<any>
constructor() {
this.onFinish = new Subject()
this.onCancel = new Subject()
this.onShow = new Subject()
this.onStart = new ReplaySubject()
this.onError = new ReplaySubject()
}
}
@Injectable({
providedIn: 'root'
})
export class ReportStoreService {
connections: Array<ReportManagerConnection> = []
constructor( public http: HttpClient ) { }
send(){
const connection = new ReportManagerConnection()
connections.push(connection)
connection.onShow.asObservable().subscribe((c)=>{
alert('Report Shown')
})
return connection
}
}
@Injectable()
export class SomeService {
constructor( public http: HttpClient, public _ReportStoreService: ReportStoreService ) { }
doSomething(){
const connection = this._ReportStoreService.send()
this.http.get('/api/test').subscribe(c=>{
connection.onShow.next({ data: c })
})
return connection
}
}
@Component({
selector: 'some-component',
templateUrl: './some-component.component.html',
})
export class SomeComponent {
public data = []
constructor(public _SomeService: SomeService) {}
loadData(){
const connection = _SomeService.doSomething()
connection.onShow.asObservable().subscribe((c)=>{
this.data = c.data
})
}
}