This post is specifically about testing UI components. I dislike testing components inside unit tests, for example with Jest. Main reasons are:
- The code is executed in a different environment and you need carefully mock any browser-only APIs that are being used.
- The point of UI is to show something for the users in the browser. It does not matter if your component has a button, but it's unclickable because there is another element on top of it.
- Debugging. When working with FE code, we have a great advantage of seeing what's wrong directly in the UI or devtools console. When using Jest, when something fails to render, element is not found is much harder to know why.
My go-to combination is to have unit tests for any non-UI logic and have e2e tests that cover the user journeys. I try to make my tests like a journey. User first makes some mistakes, which the component should validate, then the user corrects the mistakes and ultimately succeeds interactions with the component. Usually the "succeeding" part is that the view was updated accordingly.
The disadvantage is that these tests are running with actual backend and there is less room for mocking. You need to create fixutes, populate the data and somehow clear it after each tests.
There are two popular frameworks for e2e UI testing, Cypress and Playwright.
Cypress
I have a long experience with Cypress and really like the convenience of opening the test window and how I can see my test being run in real time. It has also great support for plugins. The major disadvantage is test speed and a custom implementation of Promises (chaining) which is what everyone struggles at first.
Playwright
Playwright is much faster, uses regular Promises and has a good locator API baked in. It does not run the tests in real time and only gives you videos. Altogether, the development experience is worse. By default it runs in headless mode and I had some troubles even running in headed mode where the window would close itself after tests finished running. I ended up debugging using videos, but that is much worse then debugging in Cypress.
Component testing
The silver bullet that accomplishes all reasons mentioned above is component testing. You move the rendering logic to browser, but you can still use low level testing primitives (e.g. mocks and spies).
Playwright
So far, I've only tried playwright component testing (at this time still experimental). There were two immediate pain points I realized:
- No testing primitives library. You need to install sinon or some alternative and setup the mocking logic yourself. Ideally, I'd love a Jest-like library for creating component arguments and make assertions.
- Developer experience.
Cypress
I will update this article when if I have a change to look at Cypress's component testing...