Test lit-element webcomponent with Karma
Asked Answered
M

1

0

I am trying to create a blank project, like a template, using lit-html. I wanted to also add some testing capabilities, so i have been trying to get it to work with Karma.

I can run a normal test, like an addition, without any errors, so i think Karma itself is running ok. but i can't run any test involving the webcomponent. I can't import the webcomponent!

i am exporting the webcomponent with: export default class MyComponent ...

and then on the test file i am importing it with: import MyComponent from 'pathToComponent/MyComponent'

When i run the test i get:

Error loading test file: /test/example.test.js
TypeError: Failed to fetch dynamically imported module: http://localhost:9876/base/test/example.test.js

I have it on a github repo here: https://github.com/boguz/rollup-lit-redux, so you can take a better look if you need to see what other packages i have installed.

Any help is very appreciated. Thank you!

Maccabees answered 10/9, 2020 at 19:32 Comment(0)
R
1

The error message is due to a module referenced by /test/example.test.js - the error message is a little deceptive...

Failed to fetch dynamically imported module

The clue is that you didn't dynamically import (that's when you use const module = await import('path') and you'd get an exception on that line if it failed) - you statically imported. That error message is not because it couldn't find http://localhost:9876/base/test/example.test.js, it's that it couldn't find a nested reference in that file.

At a guess example.test.js contains an import with a relative path that isn't served:

import * as testFramework from './testFramework';

export default class MyComponent...

That works in TypeScript and linting tools because it can resolve ./testFramework to ./testFramework.d.ts, ./node_modules/@types/testFramework.d.ts or whatever type lookup you're using.

However, in the browser it doesn't know you actually want ./testFramework.js or ./testFramework/index.js, it requests ./testFramework directly, gets a 404, and then gives you that error for the calling component.

In short:

  • If you statically import (i.e. with import * from ...)
  • But you get

Failed to fetch dynamically imported module: filename.js

  • The error is actually with another static import in filename.js, not getting filename.js itself.

The network tab will point you at which dependency is the problem, as it will be a 404, and the fix is either resolve these imports with your build tools, or put the full relative path to the .js file in your source.

Romine answered 13/5, 2021 at 13:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.