angular - 我的 testing.spec.ts 不起作用。错误:无法从伪造的异步测试中生成 XHR。请求网址:http://xxxxxx/v1/products
问题描述
我尝试了这个测试来测试我的服务:
显示此错误:
错误:无法从伪造的异步测试中生成 XHR。请求网址: http://xxxxxx/v1/products
测试文件
it('should return reasonable json ssss', inject([ProductService, MockBackend], fakeAsync((service: ProductService, mockBackend) => {
const mockResponse = {
data: [
{ id: 0, details: 'All cats are lions' },
{ id: 1, details: 'Video 1' },
{ id: 2, details: 'Video 2' },
{ id: 3, details: 'Video 3' },
]
};
mockBackend.connections.subscribe(connection => {
connection.mockRespond(new Response(
new ResponseOptions({
body: [
{ id: 0, details: 'All cats are lions' },
{ id: 1, details: 'Video 1' },
{ id: 2, details: 'Video 2' },
{ id: 3, details: 'Video 3' },
]
})));
});
service.productsgetall().subscribe((facts) => {
console.log(facts)
expect(facts.length).toBe(4);
});
tick();
})));
- 我的服务.ts
public productsgetall(): Observable<Products[]> {
...
return this.http.get(Api.getUrl(Api.URLS.productsgetall), {
headers: headers
}).map((response: Response) => {
let res = response.json();
if (res.StatusCode === 1) {
this.auth.logout();
} else {
return res.StatusDescription.map(aa => {
return new Products(aa);
});
}
});
}
你能问我,我的代码有什么问题,如何编写好的测试?
我的编辑代码:
TypeError:done.fail 不是函数
it('should return reasonable json ssss', (done) => {
inject([ProductService, MockBackend], async((service: ProductService, mockBackend: MockBackend) => {
const mockResponse = {
data: [
{ id: 0, details: 'All cats are lions' },
{ id: 1, details: 'Video 1' },
{ id: 2, details: 'Video 2' },
{ id: 3, details: 'Video 3' },
]
};
mockBackend.connections.subscribe(connection => {
connection.mockRespond(new Response(
new ResponseOptions({
body: [
{ id: 0, details: 'All cats are lions' },
{ id: 1, details: 'Video 1' },
{ id: 2, details: 'Video 2' },
{ id: 3, details: 'Video 3' },
]
})));
});
service.productsgetall().subscribe(facts=> {
console.log(facts);
console.log(facts[0]);
expect(facts[0].details).toEqual('ffff');
done();
});
}))();
});
解决方案
错误清楚地表明您不能使用fakeAsync
.
使用async
代替fakeAsync
it('.....', inject([ProductService, MockBackend], async((service: ProductService, mockBackend) => {
.................
service.productsgetall().subscribe((facts) => {
console.log(facts)
expect(facts.length).toBe(4);
});
tick(); // tick might not work with async
})));
推荐阅读
- apache-kafka - 如果更改了键,KStreams map() 对输出主题分区的影响
- angular - 在 fullcalendar 中实现可用性
- firebase - 错误“尝试用不同的替换对实例成员的引用”
- javascript - 如何在 JavaScript 事件上创建删除按钮
- python - Pip install matplotlib 在 M1 Mac 上失败
- sql - Oracle XMLTYPE 提取根序言值
- python-3.x - Python相对路径和绝对路径
- spring - 哪个千分尺用于从 Spring 公开简单的静态应用程序(非数字)信息?
- playwright - 运行“npx folio”时出错:第一个参数必须使用对象解构模式:_x
- javascript - Mysql insert into 语句适用于除节点 js 客户端之外的任何地方