如何在ionic2中使用http请求为提供程序编写单元测试规范?



我想测试我的提供程序类,所以我无法为提供程序编写规范。

我的提供者如下:

服务.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');
}
}

我的页面如下:

页面.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(( 的逻辑。

请帮助或分享一些链接或告诉我一些步骤,以便对此ionic2内容进行测试。

谢谢

这个Rangle教程是一个很好的起点。

你可以这样嘲笑你的提供者

class MockService {
public data = 'Test data';
getGoogle() {
return Observable.of(this.data);
}
}

将其提供给测试平台

TestBed.configureTestingModule({
declarations: [
Page1
],
providers: [
{ provide: Service, useClass: MockService }
]
});

并使用tickfakeAsync来模拟异步操作

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');
}));

最新更新