Unit Testing
WebdriverIO makes it easy to unit test components and app utility functions in the browser. Unit tests validate the code in isolation. Well written tests are fast, repeatable, and easy to reason about. It tries to follow a simple guiding principle: the more your tests resemble the way your software is used, the more confidence they can give you.
Test Setup
To resemble how your component is being used as close as possible to reality we need to render it into an actual DOM tree. WebdriverIO provides a helper package for this that you can use called @wdio/browser-runner/stencil
. It exports a render
method that allows us to mount our component to the DOM.
For example, given the following component:
loading...
We import the component into our test to render it in the browser:
loading...
You can find more information about the render
methods option and its return object in the WebdriverIO documentation.
Handle Asynchronicity
Instead of directly working on DOM objects, with WebdriverIO you are interacting with references of DOM nodes and interact through WebDriver commands that are async. Make sure you always use an await
to ensure that all commands and assertion are executed sequentially.
Missing an await
can be a simple oversight and can cause us long hours of debugging. To avoid this and ensure promises are handled properly, it is recommended to use an ESLint rule called require-await
.
Matcher
WebdriverIO provides their own matcher to assert an element in various ways. We recommend to use them over synchronous matcher like toBe
or toEqual
as they allow for retries and make your tests more resilient against flakiness.
For example, instead of asserting the content of a component like this:
expect(await $('my-component').getText()).toBe(`Hello, World! I'm Stencil 'Don't call me a framework' JS`)
It is better to use WebdriverIOs matcher for asserting text:
await expect($('my-component')).toHaveText(`Hello, World! I'm Stencil 'Don't call me a framework' JS`)
You can read more about WebdriverIOs specific matcher, in the project documentation.