hotwired / stimulus

A modest JavaScript framework for the HTML you already have
https://stimulus.hotwired.dev/
MIT License
12.55k stars 420 forks source link

Allow qunit assertions to be extended #115

Closed stuplum closed 6 years ago

stuplum commented 6 years ago

I am currently testing some DOM interactions managed by stimulus, I find the standard qunit assertions don't make for the best testing experience due to having to write for example:

this.assert.equal(this.input.hasClass('some-class-name'), true)

where input is a page object style object accessed by a getter on the testcase:

class InputElement {
  ...
  hasClass(className) {
    return includes(this.element.classList, className)
  }
  ...
}

I would like to be able to extend the qunit assertions with something like qunit-dom so that I could express the test assertion like:

this.assert.dom('input[name="whateva"]').hasClass('some-class-name')

I appreciate it might not be desired to have this as part of the core testing lib, but having the ability to extend the assertions would be great.

sstephenson commented 6 years ago

First of all, nice work getting @stimulus/test hooked up in your app without any documentation! I’d love to hear more about your setup.

As far as I know, it should be possible to use qunit-dom assertions just by importing the library. TestCase’s assert property is the same assert object you get in a QUnit test callback.

https://github.com/stimulusjs/stimulus/blob/master/packages/@stimulus/test/src/test_case.ts

sstephenson commented 6 years ago

Closing this for now since it doesn’t appear to be an issue, but please feel free to re-open with more details if things aren’t working for you.

stuplum commented 6 years ago

I managed to get it working. Our stack doesn't use typescript (except for in the stimulus tests), it wasn't possible to directly import qunit-dom, I had to import the qunit-dom assertions and extend Qunit. It's essentially what qunit-dom does, except that qunit-dom also imports qunit which causes an issue.

import DOMAssertions from 'qunit-dom/lib/assertions'

QUnit.extend(QUnit.assert, {
  dom(target, rootElement) {
    const rootEl = rootElement || this.dom.rootElement
    return new DOMAssertions(target, rootEl, this)
  }
})

I then import this file in each test that uses the assertions.

I also had to uninstall the @types/qunit as that was causing another issue.