常見問題
另請參閱主要常見問題,以了解不特定於 Angular 測試的問題。
我可以使用這個函式庫編寫單元測試嗎?
當然可以!您可以使用這個函式庫編寫單元測試和整合測試。請參閱下方關於如何模擬依賴項的更多資訊(因為這個函式庫刻意不支援淺層渲染),如果您想要對高階元件進行單元測試。這個專案中的測試展示了使用此函式庫進行單元測試的幾個範例。
當您編寫測試時,請記住
您的測試越像軟體的使用方式,它們就能給您帶來更多信心。 - 2018 年 2 月 17 日
如果我不能使用淺層渲染,我如何在測試中模擬元件?
一般來說,您應該避免模擬元件(請參閱指導原則部分)。但是,如果需要,請嘗試使用ng-mocks及其MockBuilder
。
import {Component, NgModule} from '@angular/core'
import {render, screen} from '@testing-library/angular'
import {MockBuilder} from 'ng-mocks'
@Component({
selector: 'app-parent-component',
template: '<app-child-component></app-child-component>',
})
class ParentComponent {}
@Component({
selector: 'app-child-component',
template: '<p>Child component</p>',
})
class ChildComponent {}
@NgModule({
declarations: [ParentComponent, ChildComponent],
})
export class AppModule {}
describe('ParentComponent', () => {
it('should not render ChildComponent when shallow rendering', async () => {
// all imports, declarations and exports of AppModule will be mocked.
const dependencies = MockBuilder(ParentComponent, AppModule).build()
await render(ParentComponent, dependencies)
expect(screen.queryByText('Child component')).toBeNull()
})
})
我應該測試元件樹的哪個層級?子元件、父元件,還是兩者都測試?
遵循此函式庫的指導原則,將測試的組織方式圍繞著使用者體驗和與應用程式功能互動的方式,而不是圍繞著特定的元件本身來組織測試是很有用的。在某些情況下,例如對於可重複使用的元件函式庫,將開發人員納入要測試的使用者列表中並單獨測試每個可重複使用的元件可能會很有用。其他時候,元件樹的具體分解只是一個實作細節,並且單獨測試該樹中的每個元件都可能會導致問題(請參閱https://kentcdodds.com/blog/avoid-the-test-user)。
實際上,這意味著最好在元件樹中向上測試足夠的高度,以模擬真實的使用者互動。除了這個層級之外,是否值得在更高或更低的層級上進行額外的測試,這取決於權衡以及什麼能為成本提供足夠的價值(請參閱https://kentcdodds.com/blog/unit-vs-integration-vs-e2e-tests,了解有關不同測試層級的更多資訊)。
如需更深入地討論此主題,請參閱此影片。