How to build plugins for ChaiJS?

Hi there!

Sorry, this is not well documented. :disappointed:

Here are the steps that worked for me:

  1. Clone the k6chaijs repository locally.

  2. Install the Chai plugin you wish to use. E.g. npm i chai-match. --save-dev is not strictly necessary, unless you want to build your own version of k6chaijs. I’ll explain why you might want to do that below.

    This will download the plugin into your node_modules directory.

  3. In your k6 script, import both chai and chaiMatch, and setup Chai to use the plugin. Since k6 doesn’t support Node’s require() function, the syntax is a bit different than what’s suggested on the chai-match page.

    import chai, { describe, expect } from './build/k6chaijs.min.js';
    import chaiMatch from './node_modules/chai-match/chai-match.min.js';
    
    chai.use(chaiMatch);
    
  4. Then in your k6 default function, you can use the plugin as usual. The capture() examples in the documentation worked for me.

    It’s important that you run your k6 script from the same k6chaijs directory, which is why the build and node_modules directories are specified as relative paths above.

So while this would work, it’s slightly cumbersome to ship, since you need to import directly from node_modules, and setup Chai to use the plugin in every k6 script.

An alternative approach would be to build your own k6chaijs version that bundles any plugins you need.

This is slightly more complicated:

  1. Run npm install in the kchaijs directory, to install all dependencies.

  2. Install any Chai plugins you need. --save-dev is important here, so for chai-match you would run npm i --save-dev chai-match.

  3. Change src/index.ts to setup the plugins you need. For example:

    import chai from './config';
    export { describe } from './describe';
    
    chai.use(require('chai-match'));
    
    export default chai;
    export const expect = chai.expect;
    

    Here you can use require() since this is running on Node.

  4. Run npm run-script build to build your k6chaijs bundle. It will be available in the ./build directory.

  5. Then in your k6 script you can just import describe and expect:

    import { describe, expect } from './build/k6chaijs.min.js';
    

    … and use them as usual, in addition to any plugins you installed.

The advantage of the second aproach is that you can just move the k6chaijs.min.js file around along with your k6 script, and it will have everything you need.

Should I use webpack

Webpack is not necessary in this case, since k6chaijs already uses esbuild, which is all we need to create the JS bundle. It’s specified as a dev dependency in the package.json, so npm run-script build should work without you installing it separately. (If it doesn’t, make sure that node_modules/.bin is specified in your $PATH environment variable.)

Hope this helps, and we’ll make sure to update the documentation and explain this in more detail.

1 Like