gpt4 book ai didi

angular - 使用模拟后端测试 HTTP 不起作用

转载 作者:太空狗 更新时间:2023-10-29 19:28:46 31 4
gpt4 key购买 nike

尝试做一个测试,但是得到这个错误信息:

Expected object to be a kind of Object, but was Response with status: null null for URL: null.

知道这里缺少什么吗?

登录.component.ts:

loginEvent(username, passw) {
let obj = {
user: username,
pass: passw
};

if (this.validation(obj)) {
this.httpService.loginPostToServer(obj).subscribe(
(response) => this.saveTokenToLocalstorage(response),
(error) => console.log(error)
);
}
};

http.service.ts:

loginPostToServer(data) {
return this.http.post(this.url + 'login', data);
}

测试:

import { async, TestBed, inject } from '@angular/core/testing';
import { HttpModule, Http, ResponseOptions, Response, BaseRequestOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { HttpService } from './http.service';

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

it('should be created', inject([HttpService], (service: HttpService) => {
expect(service).toBeTruthy();
}));

it('should construct', async(inject(
[HttpService, MockBackend], (service, mockBackend) => {
expect(service).toBeDefined();
})));

describe('loginPostToServer', () => {
const mockResponse = {
success: true,
token: "sample token",
user: "john"
};

const fakeUser = {
user: "john",
pass: "1234"
};

it('should parse response', async(inject(
[HttpService, MockBackend], (service, mockBackend) => {

mockBackend.connections.subscribe(conn => {
conn.mockRespond(new Response(new ResponseOptions({ body: JSON.stringify(mockResponse) })));
});

const result = service.loginPostToServer(fakeUser);

result.subscribe(res => {
expect(res).toEqual({
success: true,
token: "sample token",
user: "john"
});
});
})));
});
});

最佳答案

问题是从 http 调用返回的响应对象包含您想要的数据,但它本身并不是您想要的。

要访问请求中的数据(即请求的主体),您需要调用 .json() 方法:

  if (this.validation(obj)) { 
this.httpService.loginPostToServer(obj).subscribe(
(response) => this.saveTokenToLocalstorage(response.json()), // .json() added here
(error) => console.log(error)
);
}
};

关于angular - 使用模拟后端测试 HTTP 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44794674/

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