gpt4 book ai didi

json - 单元测试时出错 : "Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1"

转载 作者:太空狗 更新时间:2023-10-29 17:22:03 34 4
gpt4 key购买 nike

我想对服务进行单元测试,但是,在运行测试时,出现以下错误:

Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1 at MapSubscriber.project (auth.service.ts:217) at MapSubscriber.Array.concat.MapSubscriber._next (map.js:77) at MapSubscriber.Array.concat.Subscriber.next (Subscriber.js:89) at TakeSubscriber.Array.concat.TakeSubscriber._next (take.js:80) at TakeSubscriber.Array.concat.Subscriber.next (Subscriber.js:89) at ReplaySubject.Array.concat.ReplaySubject._subscribe (ReplaySubject.js:55) at ReplaySubject.Array.concat.Observable._trySubscribe (Observable.js:57) at ReplaySubject.Array.concat.Subject._trySubscribe (Subject.js:97) at ReplaySubject.Array.concat.Observable.subscribe (Observable.js:45) at TakeOperator.Array.concat.TakeOperator.call (take.js:60) at AnonymousSubject.Array.concat.Observable.subscribe (Observable.js:42) at MapOperator.Array.concat.MapOperator.call (map.js:54) at AnonymousSubject.Array.concat.Observable.subscribe (Observable.js:42) at CatchOperator.Array.concat.CatchOperator.call (catch.js:79) at AnonymousSubject.Array.concat.Observable.subscribe (Observable.js:42)

相应的行 (auth.service.ts:217) 在下面的代码中突出显示。运行应用程序工作得很好,因此我没有看到测试失败的明显原因。

注意:This SO post建议我解析对象两次。但是在运行应用程序时它不应该也会失败吗?

auth.service.ts

public login(username: string, password: string): Observable<User> {
// ...

return this.http.request(path, requestOptions).map((response: Response) => {
if (response.status === 200) {
const token = response.json().token; // <<-- Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1

const user = this.extractUser(response);
return user;
}

return null;
})
.catch(this.handleError);
}

auth.service.spec.ts

describe('AuthService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
AuthService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backend: MockBackend, options: BaseRequestOptions) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
}
],
imports: [
RouterTestingModule
],
});
});

it('should return an Observable<User>', inject([AuthService, MockBackend], (authService: AuthService, mockBackend: MockBackend) => {
mockBackend.connections.subscribe((connection: any) => {
connection.mockRespond(new Response(new ResponseOptions({
body: '{"token": "abc123", "name":"Jeff"}'
})));
});

authService.login('jeff@example.com', 'password').subscribe(user => {
expect(user.name).toEqual('Jeff');
});
}));

});

记录响应输出如下:

Response
body: ReadableStream
locked: true
__proto__: Object
bodyUsed: true
headers: Headers
__proto__: Headers
ok: true
redirected: false
status: 200
statusText: "OK"
type: "default"
url: ""
__proto__: Response

最佳答案

错误Unexpected token ... in JSON at position 1实际上意味着 JSON.parse应用于无效 JSON 的内容 - 一个随机字符串或一个根本不是字符串的值,它被强制转换为字符串。

留言Unexpected token o ...暗示解析后的值很可能是一个对象——它被强制为 [object ...]字符串。

问题在这里很明显:

Response
body: ReadableStream
locked: true
__proto__: Object
bodyUsed: true
...

这里的响应对象是全局 Response constructor的一个实例(Fetch API 的一部分),以及 ReadableStream 的存在清楚地表明了这一点。

As it can be seen in Fetch polyfill , 所有这些 res.json()确实在申请 JSON.parse一些值(value)

this.json = function() {
return this.text().then(JSON.parse)
}

这很可能是 new ResponseOptions错误地提供给全局的对象 Response构造函数,因此错误。

Angular 有类似的名字 Response class它的接口(interface)来自 Fetch Response但显然不兼容。问题是它从未被导入,因此是全局的 Response被改用了。

如何修复

应该是

import { Response, ResponseOptions, ... } from '@angular/http';

如何预防

全局变量在 Typescript 类型定义中声明,它们不能取消声明但可以在自定义类型定义中重新声明:

custom.d.ts

declare var Headers: undefined;
declare var Request: undefined;
declare var Response: undefined;
declare var URLSearchParams: undefined;

使用全局变量而不是导入的同名 Http 类会导致类型错误:

TS2532: Object is possibly 'undefined'.

只要 Angular 应用中未使用 Fetch API,这是一种理想的行为。

这不是 HttpClient 的问题取代了Http在 Angular 4.3 中并且不使用与 Fetch API 中的类同名的类

关于json - 单元测试时出错 : "Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43612837/

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