【发布时间】:2021-05-28 23:21:45
【问题描述】:
我有一个集中的 DataStore 来保存我的报表连接。这样我就可以管理报告连接事件,如 onShow、onError 和 onCancel;所以实施者不必这样做。无论如何。如何模拟 SomeService.doSomething 函数,以便它返回我的连接对象,并且它们在 onShow 主题上发出。请看我的should resolve test data 测试。我怎样才能适当地模拟这个。
mockSomeService.doSomething.and.callFake(() => {
const response = new ReportManagerConnection();
response.onShow.next({ data: [ {id: 1} ]})
return response
})
这是我的测试。
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)
}));
});
这是我的代码
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
})
}
}
【问题讨论】: