Angular 2组件中的单元测试“成功”和“错误”可观察响应 [英] Unit test 'success' and 'error' observable response in component for Angular 2

查看:96
本文介绍了Angular 2组件中的单元测试“成功”和“错误”可观察响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个调用服务OnInit的组件编写单元测试。如果响应是成功,则采取一项措施,另一项采取错误。

I'm writing a unit test for a component that makes a call to a service OnInit. If the response is a 'success' one action taken and another for an 'error'.

测试这两种情况的最佳方法是什么?我已经创建了组件和单元测试的简化版本。在这两种情况下我都可以轻松测试的东西。

What is the best way to test both cases? I've created a simplified version of the component and unit test. Something that I could easily test against in both cases.

我试图实施解决方案这里但我必须关注实现。我也试图抛出一个错误,你会在规范和评论中看到。

I've attempted to implement the solution here but I must be off on the implementation. I've also attempted to throw an error as you will see in the spec and comments.

组件

@Component({
  selector: 'app-observer-throw-unit-test',
  template: '<p>{{ data }}</p>'
})
export class ObserverThrowUnitTestComponent implements OnInit {
    public data: string;

    constructor(private _observerThrowService: ObserverThrowService) { }

    ngOnInit() {
        this._observerThrowService.getData().subscribe(
            (data) => {
                this.data = data;
            },
            (error) => {
                this.redirect()
            }
        )
    }

    redirect() {
        this.data = "Redirecting...";
    }

}

Spec

const data: string = "Lorem ipsum dolor sit amet.";

const ObserverThrowServiceStub = {
  error: false,
  getData() {
    return Observable.create((observer) => {
      if(this.error) {
        observer.error(new Error());
      } else {
        observer.next(data);
      }
      observer.complete();
    })
  }
}

describe('ObserverThrowUnitTestComponent', () => {
  let component: ObserverThrowUnitTestComponent;
  let fixture: ComponentFixture<ObserverThrowUnitTestComponent>;
  let _observerThrowService: ObserverThrowService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ObserverThrowUnitTestComponent ],
      providers: [
        { provide: ObserverThrowService, useValue: ObserverThrowServiceStub },
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ObserverThrowUnitTestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    _observerThrowService = TestBed.get(ObserverThrowService);
  });

  it('should set "data" to "Lorem ipsum dolor sit amet." on success', () => {
      expect(component.data).toEqual("Lorem ipsum dolor sit amet.");
  });

  it('should set "data" on "Redirecting..." on error',() => {
    ObserverThrowServiceStub.error = true;
    // spyOn(_observerThrowService, "getData").and.returnValue(Observable.throw("error")); // This did not work and returned : TypeError: undefined is not a constructor (evaluating 'Observable_1.Observable.throw("error")') in src/test.ts
    spyOn(_observerThrowService, "getData")
    expect(component.data).toEqual("Redirecting...");
  });

  it('should set "data" on "Redirecting..." on error',() => {
    // This works after setting error to true in the previous test
    spyOn(_observerThrowService, "getData")
    expect(component.data).toEqual("Redirecting...");
  });

});


推荐答案

我会创建两个模拟 - 一个抛出错误:

I would create two mocks - one that throws an error:

class ObserverThrowServiceStub {
  getData() {
    return Observable.throw(new Error('Test error'));
  }
}

以及成功返回的。

class ObserverSuccessServiceStub {
  getData() {
    return Observable.from(data);
  }
}

然后,不是向所有人提供相同的模拟服务测试,您根据相关测试适当地提供失败/成功的模拟服务(显然,您需要将模块配置移动到您在每个测试中而不是在中调用的可配置方法。 beforeEach()代码。

Then, instead of providing the same mock service to all tests, you provide the failing/successful mock service appropriately depending on the test in question (obviously you'll need to move your module configuration into a configurable method that you call from within each test rather than in the .beforeEach() code.

这里有一篇关于使用Observables测试Angular服务的非常好的文章(它正好使用了这个模型):
http://www.zackarychapple.guru/angular2 /2016/11/25/angular2-testing-services.html

There is a really nice article on testing Angular services using Observables here (which uses exactly this model): http://www.zackarychapple.guru/angular2/2016/11/25/angular2-testing-services.html

这篇关于Angular 2组件中的单元测试“成功”和“错误”可观察响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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