Skip to main content

Journal

Testing Stimulus Controllers

Stimulus JS is great but doesn’t provide any documentation for testing controllers, so here’s some of my own that I’ve picked up.

Required 3rd-party libraries

Basic Test

// hello_controller.test.js
import { Application as StimulusApp } from "stimulus";
import HelloController from "path/to/js/hello_controller";

describe("HelloController", () => {
beforeEach(() => {
// Insert the HTML and register the controller
document.body.innerHTML = `
<div data-controller="hello">
<input data-target="hello.name" type="text">
<button data-action="click->hello#greet">
Greet
</button>
<span data-target="hello.output">
</span>
</div>
`
;
StimulusApp.start().register('hello', HelloController);
})

it("inserts a greeting using the name given", () => {
const helloOutput = document.querySelector("[data-target='hello.output']");
const nameInput = document.querySelector("[data-target='hello.name']");
const greetButton = document.querySelector("button");
// Change the input value and click the greet button
nameInput.value = "Laurence";
greetButton.click();
// Check we have the correct greeting
expect(helloOutput).toHaveTextContent("Hello, Laurence!");
})
})

Clair and I just watched The Farewell, a comedy-drama film written and directed by Lulu Wang starring Awkwafina and Zhao Shuzhen, and really enjoyed it. Interesting/difficult subject matter and really nicely done. If you need a break from grisly murder cases etc then I can heartily recommend it.

As I got on my usual bus from Stockwell St to Vic Rd this eve, I noticed it was the same driver whose bus I’d taken twice last week and both times it had broken down – that’s two days in a row – leaving me to walk home in the usual January post-apocalyptic shitstorm. I got on his bus today and no sooner was it 200 yards down the road than it crashed into a taxi, across from Marks and Sparks. Everybody out – again. That’s 3 times I’ve been on his bus, and three times it’s broken down for one reason or another. The shittest hat-trick ever 😂. I need to find out this guy’s name so I can never get on a plane with him.

External Link Bookmark Note Entry Search