错误:没有MockBackend的提供者!当为angular2 final写单元测试时

时间:2016-12-05 10:34:58

标签: unit-testing angular

我正在为angular2 - karma - jasmine写单元测试。

我在服务调用API时使用mockBackend来响应数据。 这是我的代码

    function Connection(mockBackend) {
          connection.mockRespond(new Response(
              new ResponseOptions({
                      body: JSON.stringify(lookup)
                   }
              )));
        });
    }

describe('Update Contact Details Test', () => {
      let fixture, comp;

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

        TestBed.configureTestingModule({
                declarations: [ ContactFieldListComponent ],
                providers: _.union(DEFAULT_PROVIDERS, [FieldService, LookupsService, ContactService]),
                schemas: [CUSTOM_ELEMENTS_SCHEMA],
                imports: DEFAULT_IMPORT
            })
            .compileComponents().then(() => {
                fixture = TestBed.createComponent(ContactFieldListComponent);
                comp = fixture.componentInstance;
            });
    })));

    it('get contact field list', () => 
        expect(1).toBe(1);
    });
});

它无法处理错误Error: No provider for MockBackend! 我该如何解决?

1 个答案:

答案 0 :(得分:4)

看起来您错过了将MockBackend添加到TestBed的提供程序中。

...
TestBed.configureTestingModule({
            declarations: [ ContactFieldListComponent ],
            providers: _.union(
                DEFAULT_PROVIDERS, [
                    FieldService, 
                    LookupsService, 
                    ContactService,
                    MockBackend // <- add it here
                ]),
            schemas: [CUSTOM_ELEMENTS_SCHEMA],
            imports: DEFAULT_IMPORT
        })
...

另外我认为你必须在TestBed下创建另一个beforeEach,因为在第一个中,MockBackend没有注册。

我为您准备了一个示例测试,或许可以帮助您:https://github.com/angular-workshops/angular2-testing/blob/solution/tour-of-heroes/src/app/hero.service/hero.service.shallow.spec.ts

相关问题