Angular 4单元测试与jasmine / karma与http post mocking - 如何修复 [英] Angular 4 unit testing with jasmine /karma with http post mocking - how to fix

查看:114
本文介绍了Angular 4单元测试与jasmine / karma与http post mocking - 如何修复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务我想在角4打字茉莉花中进行单元测试。

I have a service I want to unit test in angular 4 typescript jasmine.

现在, http 正在做帖子,然后它会返回一个标识,但是它没有发送任何内容。

Now, the http is doing a post , and it returns an identity, however.. it is not sending anything.

我想要有良好的代码覆盖率,但我不明白如何完成这个嘲弄声明。

I want to just have good code coverage but i don't understand how to quite complete this mocking statement.

这是我服务文件中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 FILE ,我没有得到真正的测试,我想假设我从服务http帖子收到一个号码,响应应该像 000000014

Then the SPEC FILE , which i don't get what to really test, i suppose faking that i received a number back from the service http post, the response should be something like 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正常相同的函数;另一件事是你的测试不应该是真正的服务器,所以你需要这样的东西(你可能需要添加其他依赖项):

In order to achieve what you want, the mock you need is a simple function that returns the same as the POST would do normally; another thing is your test should not hit the server for real, so you would need something like this (you might need to add other dependencies):

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

这篇关于Angular 4单元测试与jasmine / karma与http post mocking - 如何修复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆