qunitjs / qunit

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

importing .css file using webpack css-loader/style-loader causes: TypeError: Unknown file extension ".css" #1719

Closed matthewcornell closed 10 months ago

matthewcornell commented 1 year ago

Tell us about your runtime:

What are you trying to do?

I'm trying to change a JavaScript ES6 module I'm writing to be a Node.js project (so that I can use Ajv.js), and (following the webpack tutorial) I've added import './mystyles.css'; to a file that my Qunit-based tests use. The tests worked fine before, but now I get this error:

TypeError: Unknown file extension ".css" for /Users/.../mystyles.css

IIUC, import './mystyles.css'; is non-standard JavaScript that's processed and removed by webpack when I build the project.

My question is: Is there a way to allow Qunit to run and somehow ignore that import? If not, is there a different approach that I should take that would allow me to avoid this non-standard JavaScript import call?

(Note that I am a beginner JavaScript/css/node/etc developer, and until now I've simply used css files via a link in the head, e.g., <link rel="stylesheet" href="mystyles.css"> . Maybe I should go back to that?)

matthewcornell commented 1 year ago

Following up, I believe I got this working by extracting import './mystyles.css'; to a separate .js file and then adding that file to the webpack.config.cjs's entry section. Note that the order in that section was significant. I would still welcome your comments, thanks.

Krinkle commented 1 year ago

@matthewcornell I generally recommend against use of non-standard JavaScript.

However, QUnit does not mind if you use alternative JavaScript compilation targets such as CoffeeScript, TypeScript, Webpack-customised imports, or Babel (for new Ecma syntax in current browsers). In that case, you will have to build your source code first and import the output of your build process in your test suite, rather than your underlying source files. This is similar to what your application would do, and makes the test more representative of what your application will be experiencing as well.

There are a number of different ways to do this. When testing your code within Node.js, you can use the --require option of the QUnit CLI to register an automatic pre-processing step that will automatically handle Babel and TypeScript. I don't recall if Webpack supports something like this, if it does, you could use that.

Otherwise, you may have to add an explicit step before your test command. For example, in package.json, you might write

"test": "esbuild && qunit"

Or,

"build": "webpack …",
"test": "npm run build && qunit",
"test-watch": "qunit -w",

Naturally, you can combine the watch modes as well. For example, you might have npm run build-watch open in one terminal tab, and npm run test-watch open in another.