Gaet
Gaet

Reputation: 689

How to do unit testing on an aurelia module?

I'm trying to unit test a home-made NPM module of aurelia components. Note that this is not an aurelia application, it's just a repository of components and classes!

For this, I tried to replicate the setup of aurelia-dialog but I still have a few problems that really prevent me from passing a single test in a useful way...

  1. karma is extremely slow to start: close to 1 minute before the first test runs
  2. html templates for components are not served to the client although they are loaded by jasmine : I receive a 404 when the browser requests it but the karma console output shows the file loaded
  3. I unfortunately have to use jquery as an npm dependency and I can't find how to load it for jasmine, which makes it impossible to even load a component using it...

Thanks a lot!

Upvotes: 1

Views: 546

Answers (1)

Fred Kleuver
Fred Kleuver

Reputation: 8047

Replicating the aurelia-dialog setup is probably not going to help because it no longer has any html files. They inlined html in the typescript sources, to make it easier for consumers to bundle (and possibly easier to test as well..)

  1. Karma is only as fast as the bundler/transpiler you integrated it with, and of course depends on how many files you are loading. Double check that you're not including/serving files you don't need:

    • You need to include+watch the src and test folder
    • You should include node_modules and other deps, but not watch them
    • Any other stuff such as build assets/scripts, custom typings should be excluded
  2. There's always a module loader handling these requests for files coming from inside your app. They live in "virtual" paths. When you directly request the file from the browser, you're bypassing this and requesting something that likely doesn't exist (or isn't served), even though your app can access it.

  3. Loading dependencies like jQuery (or Bluebird for that matter) is done similarly to how you'd normally do it in your app. Have a direct reference to the path in your node_modules folder from your bundle config. Then make sure it's either prepended to your bundle, or served standalone. In the latter case, simply import "jquery" in your setup.ts. Or look at how Bluebird is included in my suggestion below.

A suggestion

If speed is a concern, I would recommend to try using karma in combination with webpack. That's typically very fast (especially since webpack 4) and it greatly simplifies serving additional assets.

This plugin skeleton should give you a good idea of how these various things all work together.

Here's an example of how to configure karma with webpack

Then to add html assets for testing, simply add the html-loader below ts-loader like so (as you can see here):

    {
      test: /\.html$/,
      use: [{ loader: "html-loader" }]
    },

Disclaimer: I am the author of aforementioned plugin skeleton

Upvotes: 1

Related Questions