我想测试我的提供者类,所以我无法为提供者编写规范。
我的提供者如下:
service.ts
//imports are done correctly.
@Injectable()
export class Service {
constructor(private http: Http) { }
getGoogle():Observable<any> {
console.log("Inside service");
return this.http.get('https://jsonplaceholder.typicode.com/posts/1');
}
}
我的page.ts如下:
page.ts
//imports are done correctly.
export class Page1 {
constructor(private service: Service, private navCtrl: NavController) { }
async get() {
console.log("inside get method");
const data = await this.service.getGoogle().toPromise();
console.log('The response is' , data);
}
}
service.spec.ts
//imports are done correctly
describe('Service', () => {
let comp: Service;
let fixture: ComponentFixture<Service>;
let de: DebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [],
imports: [
IonicModule.forRoot(Service)
],
providers: [Http]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Service);
comp = fixture.componentInstance;
de = fixture.debugElement;
});
afterEach(() => {
fixture.destroy();
});
it('test the http request to te server', ()=>{
//code to test http request of the Service class
});
});
所有导入都正确完成,只需要测试使用http.get()测试getGoogle()的逻辑。
请帮助或分享一些链接或告诉我一些步骤,以便测试这种离子2含量。
谢谢
答案 0 :(得分:0)
This Rangle tutorial是一个很好的起点。
您可以像这样嘲笑您的提供商
class MockService {
public data = 'Test data';
getGoogle() {
return Observable.of(this.data);
}
}
将其提供给TestBed
TestBed.configureTestingModule({
declarations: [
Page1
],
providers: [
{ provide: Service, useClass: MockService }
]
});
使用tick
和fakeAsync
来模拟异步操作
it('should get', fakeAsync(() => {
comp.get();
tick();
// If you want to assign the data to a class variable. If not, change the
// condition for whatever you want to test the method to do.
expect(comp.data).toEqual('Test data');
}));