Angular 4 - 测试组件中的http.get调用,但不在外部服务中

时间:2018-01-15 15:39:02

标签: angular unit-testing

我对测试很糟糕,我确信这里的答案非常简单,但我有一点精神障碍,所以感谢任何可以提供帮助的人。在我的组件中,我加载了这样的静态JSON文件,注意我没有使用服务,我直接调用http对象:

public crispList: any;

public ngOnInit() {
  this.crispList = this.http.get('path/to/crisp-flavors.json').map((res: any) => {
        const respJson = res.json();
        return respJson.walkers.crisps;
      });
  }
}

我想测试一下我的测试文件中是否填充了crispList,我在我的测试文件中写了以下内容,但我不确定如何调用/模拟this.http.get调用,因为我希望a)测试进行调用并且b)属性/变量crispList具有我模拟的值,这里是我的测试代码:

describe('CrispFlavourComponent', () => {
  let backend: MockBackend = null;
  let componentFixture: any;
  const mockResponse = {
    walkers: {
      crisps: [
          {
            name: 'Salt & Vinegar',
          }, {
            name: 'Cheese & Onion',
          }

        ]
      }
    }
  };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes([
          {path: '**', component: DummyComponent}
        ]),
        TranslateI18NextTestingModule.forRoot()],
      declarations: [
        DummyComponent, CrispFlavorComponent
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [
        MockBackend,
        BaseRequestOptions,
        {
          provide: Http,
          useFactory: (backendInstance: MockBackend, defaultOptions: BaseRequestOptions) => {
            return new Http(backendInstance, defaultOptions);
          },
          deps: [MockBackend, BaseRequestOptions]
        }]
    });

    TestBed.compileComponents().then(() => {
      componentFixture = TestBed.createComponent(CrispFlavourComponent);
    });

  }));u

  beforeEach(inject([MockBackend], (mockBackend: MockBackend) => {

    backend = mockBackend;
    backend.connections.subscribe((connection: MockConnection) => {
      const options = new ResponseOptions({
        status: 200,
        body: JSON.stringify(mockResponse)
      });
      return connection.mockRespond(new Response(options));
    });

    it('should load the list of Crisp Flavors', () => {
    const instance = componentFixture.componentInstance;
    instance.ngOnInit();
    // this.http.get('path/to/crisp-flavors.json').subscribe((res) => {
    // expect("something") or expect instance.crispList is the mocked value
    // })
  });

注意注释掉的部分,这里我想进行http调用或模拟调用以测试模拟结果。任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:1)

我看到你正在回归成功。

在这种情况下,你应该像你一样,拨打你的电话ngOnInit

但首先,你应该在你的方法上创建间谍。

首先设置你的间谍:

const instance = componentFixture.componentInstance;
// Array notation for I don't know if your http is private
spyOn(instance['http'], 'get').and.callThrough();
instance.ngOnInit();

现在,您所要做的就是测试您的通话是否已经完成,以及答案是否正确:

expect(instance['http']['get']).toHaveBeenCalledWith('path/to/crisp-flavors.json');
expect(instance.crispList).toEqual(mockResponse.walkers.crisps);

之后,请记住模拟错误并测试组件在这种情况下的作用!