gpt4 book ai didi

使用 jasmine/karma 和 http post mocking 进行 Angular 4 单元测试 - 如何修复

转载 作者:太空狗 更新时间:2023-10-29 17:15:01 25 4
gpt4 key购买 nike

我有一项服务,我想在 angular 4 typescript jasmine 中进行单元测试。

现在,http 正在做一个 post ,它返回一个身份,但是..它没有发送任何东西。

我只想拥有良好的代码覆盖率,但我不明白如何完成这个模拟语句。

这是我的服务文件中的http post方法

addSession() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

return this.http.post(this.url, JSON.stringify({}), options)
.map((response: Response) => response.json());

}

然后是 SPEC 文件 ,我不知道要真正测试什么,我想假装我从服务 http post 收到了一个数字,响应应该类似于 000000014

规范

import { TrackerFormService } from './tracker-form.service'
import { Observable } from 'rxjs/Observable'

describe('TrackerFormService', () => {

let trackerFormService: TrackerFormService,
mockHttp;

beforeEach(() => {
mockHttp = jasmine.createSpyObj('mockHttp', ['get', 'post', 'put']
)
trackerFormService = new TrackerFormService(mockHttp);
});

describe('addSession', () => {

it('add session ', () => {
// how to test, what to test?
// response , is a number? how to mock/fake this?

})

})

})

最佳答案

为了实现你想要的,你需要的模拟是一个简单的函数,它返回与 POST 正常执行的相同的函数;另一件事是你的测试不应该真正命中服务器,所以你需要这样的东西(你可能需要添加其他依赖项):

import { HttpModule } from '@angular/http';
import { TrackerFormService } from './tracker-form.service'
import { Observable } from 'rxjs/Observable'

describe('TrackerFormService', () => {
// Mock the service like this and add all the functions you have in this fashion
let trackerFormService: TrackerFormService,
mockService = {
addSession: jasmine.createSpy('addSession').and.returnValue(Observable.of('your session object mock goes here'))
};

beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [{
provide: TrackerFormService,
useValue: mockService
}]
});
});

// Do this trick to inject the service every time, and just use `service` in your tests
beforeEach(inject([TrackerFormService], (trackerFormService) => {
service = trackerFormService;
}));

describe('addSession', () => {
it('add session ', () => {
let fakeResponse = null;

// Call the service function and subscribe to it to catch the fake response coming from the mock.
service.addSession().subscribe((value) => {
// in here value will be whatever you put as returnValue (remember to keep the observable.of())
fakeResponse = value;
});

// expects as in any test.
expect(fakeResponse).toBeDefined();
expect(fakeResponse).toBe('your session object mock goes here');
});
});
});

关于使用 jasmine/karma 和 http post mocking 进行 Angular 4 单元测试 - 如何修复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46420640/

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