2017-05-26 43 views
0

我有一个组件,它通过服务从服务器加载一些数据并显示它。拆分包含异步的角度组件单元测试

我写了下面的测试组件(工作):

... 
it('Should contains data after loading', async(() => { 
    fixture.whenStable().then(() => { 
     fixture.detectChanges(); 
     expect(element.querySelector('h1').textContent.trim()).toBe(expectedTitle); 
     expect(element.querySelector('p').textContent.trim()).toBe(expectedParagraph); 
     element.querySelectorAll('ul > li').forEach((li, index) => { 
      expect(li.textContent.trim()).toBe(expectedListItem[index]); 
     }); 
    }); 
})); 

是否有可能将所有预计分成单独it测试?

我想有这样的事情:

... 
describe('Component contains data after loading', async(() => { 
    fixture.whenStable().then(() => { 
     fixture.detectChanges(); 

     it('Should contain title',() => { 
      expect(element.querySelector('h1').textContent.trim()).toBe(expectedTitle); 
     }); 

     it('Should contain paragraph',() => { 
      expect(element.querySelector('p').textContent.trim()).toBe(expectedParagraph); 
     }); 

     it('Should contain list',() => { 
      element.querySelectorAll('ul > li').forEach((li, index) => { 
       expect(li.textContent.trim()).toBe(expectedListItem[index]); 
      }); 
     }); 
    }); 
})); 

但我在describe线得到错误Argument of type '(done: any) => any' is not assignable to parameter of type '() => void'

编辑:

新增TestBed设置。

beforeEach(async(() => { 
    serviceMock = prepareServiceMock(); 
    TestBed.configureTestingModule({ 
     declarations: [ 
      TestComponent 
     ], 
     providers: [ 
      { provide: TestService, useValue: serviceMock } 
     ] 
    }).compileComponents(); 
})); 

beforeEach(() => { 
    fixture = TestBed.createComponent(TestComponent); 
}); 
+0

你的'TestBed'配置在哪里? –

回答

0

每个测试规格将单独执行。因此,您可以在新规格开始时每次拨打fixture.detectChanges();

it('Should contain title', async(() => { 
    fixture.detectChanges(); 
    fixture.whenStable().then(() => { 
    expect(element.querySelector('h1').textContent.trim()).toBe(expectedTitle); 
} 
})); 

it('Should contain paragraph', async(() => { 
     fixture.detectChanges(); 
     fixture.whenStable().then(() => { 
     expect(element.querySelector('p').textContent.trim()).toBe(expectedParagraph); 
    } 
})); 

确保每次创建新组件。

beforeEach(() => { 
     fixture = TestBed.createComponent(MyComponent); 
}); 
+0

因此,不可能将'whenStable()。then'代码提取到一个公共块中? – piotrgajow

+0

在我的项目中没有真正尝试过这种方式。 –