gpt4 book ai didi

angular - 我的 testing.spec.ts 不工作。错误: Cannot make XHRs from within a fake async test. 请求网址:http://xxxxxx/v1/products

转载 作者:行者123 更新时间:2023-11-28 20:10:42 36 4
gpt4 key购买 nike

我试过这个测试来测试我的服务:

显示这个错误:

Error: Cannot make XHRs from within a fake async test. Request URL: 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 is not a function

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

image

最佳答案

错误清楚地表明您不能使用 fakeAsync 发出 XHR 请求。

使用 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
})));

关于angular - 我的 testing.spec.ts 不工作。错误: Cannot make XHRs from within a fake async test. 请求网址:http://xxxxxx/v1/products,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50605994/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com