Skip to content

Instantly share code, notes, and snippets.

@web-padawan
Last active October 5, 2020 07:34
Show Gist options
  • Save web-padawan/ce6cdac378faca389f41f7b97da79028 to your computer and use it in GitHub Desktop.
Save web-padawan/ce6cdac378faca389f41f7b97da79028 to your computer and use it in GitHub Desktop.

Using @web/dev-server

Documentation: https://modern-web.dev/docs/test-runner/overview/

Writing tests

Libraries

Import @esm-bunde/chai:

import { expect } from '@esm-bunde/chai';

Import sinon:

import sinon from 'sinon';

Fixtures

Use fixture or fixtureSync from @open-wc/testing-helpers. When using Polymer 3, the only difference is that fixture uses requestAnimationFrame (with LitElement it performs await element.updateComplete instead).

Using fixtureSync

beforeEach(() => {
  scroller = fixtureSync(`
    <vaadin-infinite-scroller buffer-size="80">
      <template>
        <div>[[index]]</div>
      </template>
    </vaadin-infinite-scroller>
  `);
});

Using fixture

beforeEach(async () => {
  datepicker = await fixture(`<vaadin-date-picker></vaadin-date-picker>`);
});

Positioning

Unlike WCT, there is no separate <iframe> where tests run. So the fixture is rendered below test report. This may affect some tests, especially overlay alignment. Use position: absolute to prevent this:

beforeEach(() => {
  overlay = fixtureSync(`
    <vaadin-date-picker-overlay-content
      style="position: absolute; top: 0"
    ></vaadin-date-picker-overlay-content>`);
});

Helpers

Use aTimeout and nextFrame from @open-wc/testing-helpers:

Using nextFrame

it('should request availability from IronA11yAnnouncer', async () => {
  const spy = sinon.spy(IronA11yAnnouncer, 'requestAvailability');
  datepicker.open();
  await nextFrame();
  expect(spy.called).to.be.true;
});

Using aTimeout

it('should render correct week numbers for Feb 2016', async () => {
  const month = new Date(2016, 1, 1);
  monthCalendar.month = month;
  await aTimeout();
  const weekNumbers = getWeekNumbers(monthCalendar);
  expect(weekNumbers).to.eql([5, 6, 7, 8, 9]);
});

Spies

There is no plugin for sinon-chai at the moment, so the syntax needs to be changed:

Before:

expect(spy).to.be.called;
expect(spy).to.be.calledTwice;

After:

expect(spy.called).to.be.true;
expect(spy.callCount).to.equal(2)

Debug

  1. Run with --manual flag to get a tests page URL.

  2. Open URL in a browser and click a test file to debug.

Coverage

  1. Coverage uses v8-to-istanbul and only works in Chrome.

  2. Use /* c8 ignore next */ to ignore next line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment