qunitjs / qunit

🔮 An easy-to-use JavaScript unit testing framework.
https://qunitjs.com
MIT License
4.02k stars 783 forks source link

Add DOM hook to allow links to be added after the Rerun link #1717

Open david-pfx opened 1 year ago

david-pfx commented 1 year ago

Using 2.19.4, Windows, browser New feature: Add DOM hook to allow links to be added after the Rerun link Eg link to source code, link to docs, link to Git etc Can already be done by walking the tree, but a better method would add value.

Krinkle commented 1 week ago

@david-pfx Coud you share an example or two of the kind of links you'd like to insert, and what (if any) test information you use to builld the links?

I've recently documented the beginnings of the "HTML API" at https://qunitjs.com/browser/#html-api

Here is how you might use it:

Screenshot
QUnit.hooks.afterEach(function () {
  const test = QUnit.config.current;
  const testItem = document.querySelector('#qunit-test-output-' + test.testId);
  const assertList = testItem.querySelector('ol');

  // Append "View source" link
  const fileName = /.*\/([^/:]+):/.exec((test.stack || '').split('\n')[0])?.[1];
  if (fileName) {
    const url = `https://github.com/search?type=code&q=${encodeURIComponent('org:qunitjs path:"' + fileName + '"')}`;
    testItem.insertBefore(
      Object.assign(document.createElement('a'), {
        href: url,
        textContent: 'View source'
      }),
      assertList
    );
  }
});

I suspect this is close to what you have already, but I figured I'd recognise and support it. We could ease this by wrapping "Rerun" in a <span> with a documented class like qunit-test-actions that you can safely append to, instead of having to manually position it relative to "runtime" and "assert-list":

QUnit.hooks.afterEach(function () {
  const test = QUnit.config.current;
  const testActions = document.querySelector(`#qunit-test-output-${test.testId} .qunit-test-actions`);

  // Append "View source" link
  const fileName = /.*\/([^/:]+):/.exec((test.stack || '').split('\n')[0])?.[1];
  if (fileName) {
    const url = `https://github.com/search?type=code&q=${encodeURIComponent('org:qunitjs path:"' + fileName + '"')}`;
    testActions.append(Object.assign(document.createElement('a'), {
      href: url,
      textContent: 'View source'
    }));
  }
});

A more constrained but declarative API could look like this:


QUnit.on('htmlTestActions', (e) => {
  e.status; // "passed"
  e.testDone; // https://qunitjs.com/api/callbacks/QUnit.testDone

  e.actions.push({
    url: '…',
    label: 'View source'
  });
});