nimblehq / rails-templates

Our optimized Rails templates used in our projects

Home Page:https://nimblehq.co

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add Jest to test javascript and Stimulus controllers

malparty opened this issue · comments

Why

Since the end of 2019, Jest jsdom has supported MutationObserver, so we don't need to rely on Babel anymore. Jest also supports code transformation via ESBuild.

So it would make sense to provide a ready-to-work test config when the hotwire add-on is selected.

After discussion with Olivier, some concerns were shared:

Yet another framework, cognitive load is increased 🧠

Adding JEST means adding multiple dependencies (including Babel).
But it also means adding different testing tools and API (what method names for which assertion? What to test? How to test it? ...)

TODO

Testing with HTML sample does not increase our confidence

In previous Rails projects, JEST was introduced in order to cover the tests of some Vanilla JS components following compass conventions (per screen classes).
This experience resulted in tests that must copy a lot of HTML to remain in sync with the screen. 2 issues appeared:

  • low maintainability (each change in the screen/view required the test to be adjusted too)
  • low confidence in the test (if the test has false negatives after any code change, it cannot help you be confident about your code)

My experience with Stimulus was quite different.
Stimulus controllers must NOT be mapped to a screen. They must cover reusable behaviors. This reusability makes them better candidates for tests that JS classes specific to a single screen.
I think my understanding is shared by the community:

  • "Stimulus controllers are often general-purpose and under 50 lines of code." (from boringrails.com).
  • "In turn, Stimulus helps you build small, reusable controllers, giving you just enough structure to keep your code from devolving into “JavaScript soup.”" (from the Stimulus handbook)

Some points of attention:

  • Jest testing interface does not seem very convenient to test from the outside, so it's a bit tricky to interact with the UI elements (stimulus controllers use a LOT of events)
  • ...

What are the alternatives?

  • Phlex: No system tests ⛔ (but it does not mean Phlex is bad... it's surprisingly awesome!!)
  • ViewComponents ⌛ (testing in progress, so far I just feel it is a bit overkilled)
  • ...?

Who Benefits?

Developers on projects that require some JS logic.

Closing in Favor of View Component (an engineering showcase will be needed though).
Only view components allow UI test, with JS and CSS interactions, yet in isolation. The isolated version of the component is called a preview and used in the dev/test envs only, allowing better documentation and testability. A stimulus controller tested in a View Component can still be used the traditional way (i.e. in multiple partial views or other components).