Angular 6 for Enterprise:Ready Web Applications
上QQ阅读APP看书,第一时间看更新

Angular e2e tests

In addition to unit tests, Angular CLI also generates and configures e2e tests for your application. While unit tests focus on isolating the class-under-test, e2e tests are about integration testing. Angular CLI leverages Protractor along with WebDriver, so you can write automated acceptance tests (AAT) from the perspective of a user interacting with your application on a browser. As a rule of thumb, you should always write an order of magnitude more unit tests than AATs, because your app changes frequently and as a result, AATs are vastly more fragile and expensive to maintain compared to unit tests.

If the term web driver sounds familiar, it's because it is an evolution of the canonical Selenium WebDriver. As of March 30th, 2017, WebDriver has been proposed as an official web standard at the W3C. You read more about it at https://www.w3.org/TR/webdriver. If you're familiar with Selenium from before, you will feel right at home, since a lot of the patterns and practices are near identical.

The CLI provides e2e tests for the initial AppComponent and depending on the complexity and the feature set of your application, it is up to you to follow the provided pattern to better organize your tests. There two files generated per component under the e2e folder:

e2e/app.e2e-spec.ts
import { AppPage } from './app.po'

describe('web-app App', () => {
let page: AppPage

beforeEach(() => {
page = new AppPage()
})

it('should display welcome message', () => {
page.navigateTo()
expect(page.getParagraphText()).toEqual('Welcome to app!')
})
})

app.e2e-spec.ts is written in Jasmine and implements acceptance tests. The spec is dependent upon the page object (po) file, which is defined beside the spec file:

e2e/app.po.ts
import { browser, by, element } from 'protractor'

export class AppPage {
navigateTo() {
return browser.get('/')
}

getParagraphText() {
return element(by.css('app-root h1')).getText()
}
}

The page object file encapsulates web driver implementation specifics from the spec file. AATs are the most. This results in easy-to-maintain, human-readable spec files. By separating concerns at this level, you isolate fragility of AATs to one location. By leveraging class inheritance, you can build a robust collection of page objects that can be easier to maintain over time.