2017-05-26 42 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

在我的項目中沒有真正嘗試過這種方式。 –