我尝试测试服务,http post,就像下面的代码一样。
我按照此post进行测试,但发生错误。
我的服务代码:
public CreateProduct(newProd: Product): Observable<boolean> {
.....
let body = newProd.generateUrlencodedParameters(this.currentuser().token);
return this.http.post(API.getUrl(Api.URLS.CreateProduct), body, {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 0) {
return true;
}
}
我的班级产品:
export class Product{
id: number;
prod_number: String;
prod_name: string;
constructor(obj: any) {
this.id= obj.id;
this.prod_number= obj.prod_number;
this.prod_name= obj.prod_name;
}
public generateUrlencodedParameters(token: string, id?: number): string
{
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('prod_number', this.prod_number.toString());
urlSearchParams.append('prod_name', this.prod_name.toString());
urlSearchParams.append('token', token);
return urlSearchParams.toString();
}
}
我尝试了这段代码来测试我的服务代码:
describe('Create Product ', () => {
let trackerFormService: ProductService,
mockService = {
createProduct: jasmine.createSpy('createProduct').and.returnValue(Observable.of('your session object mock goes here'))
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [{
provide: ProductService,
useValue: mockService
}] }); });
beforeEach(inject([ProductService], (trackerFormService) => {
service = trackerFormService;
}));
describe('createProduct', () => {
it('add session ', () => {
let fakeResponse = null;
service.CreateProduct().subscribe((value) => {
fakeResponse = value;
}); }); });});
结果是:
ReferenceError:未定义服务
请您,您能告诉我任何想法,如何解决此问题,或任何测试服务帖的示例。
日Thnx。
答案 0 :(得分:0)
一种方法是更改beforeEach函数,如下所示:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [{
provide: ProductService,
useValue: mockService
}] });
service = TestBed.get(ProductService);
});
编辑:
describe('Create Product ', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [{
provide: ProductService,
useValue: mockService
}] });
});
it('add session ', inject([ProductService], (service: ProductService) => {
let fakeResponse = null;
service.CreateProduct().subscribe((value) => {
fakeResponse = value;
});
})
});
编辑:您可以对ProductService使用假货。但这意味着您没有测试ProductService。我不确定你在这里试试什么。
您可以尝试:(注意传递的参数)
mockService = {
createProduct: (newProduct) => jasmine.createSpy('createProduct').and.returnValue(Observable.of(false))
};
或者在新文件中创建以下类。
export class FakeProductService {
public CreateProduct(newProd: Product): Observable<boolean> {
return Observable.of(false);
}
}
在您的测试文件中。
describe('Create Product ', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [{
provide: ProductService,
useClass: FakeProductService
}] });
});
it('add session ', inject([ProductService], (service: ProductService) => {
let fakeResponse = null;
service.CreateProduct(\*new Product()*\).subscribe((value) => {
fakeResponse = value;
});
})
});