developit / htm

Hyperscript Tagged Markup: JSX alternative using standard tagged templates, with compiler support.
Apache License 2.0
8.64k stars 169 forks source link

Testing Library with Preact + HTM Example #227

Closed RapidOwl closed 1 year ago

RapidOwl commented 1 year ago

Hi folks, I've got a small application working (without any build tools) and it's a lovely way to work, but now I'm trying to add some automated tests. I've got Jest and Testing Library set up, but I just get the following error:

image

Here's the test code and the repository + branch with the whole thing is here: https://github.com/RapidOwl/qaas/tree/testing

import { expect } from 'expect';
import { render, fireEvent, screen } from '@testing-library/preact';

import { h, html } from 'htm/preact';

import Result from './quiz';

describe('Result', () => {
    test('should display image', () => {
        const { getByAltText } = render(html`<${Result}/>`);

        const image = getByAltText('the_alt_text');

        expect(image.src).toContain('http://www.images.com/lol.png');
    });
});

I'm assuming the problem is with render(html<${Result}/>);, but I have no idea what correct code would look like here.

Are there any examples of other people doing this that I can crib from?

The test also errors if I try and import the modules via URL so I've had to install the modules, which means it no longer just works in the browser. Am I missing some more config somewhere? I really want to avoid the whole build step part, but also test my code.

Solution:

I gave up on Jest because I got embroiled in ESM vs CJS madness.

I went back to Vitest with the following config and it seems to work:

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    environment: 'jsdom'
  },
})

The tests now run and I'm stuck trying to figure out how to make fetch work in my tests 😂.