0

I have a Vue project which was created using Vue CLI v3.5 and am trying to write some component unit tests. I have jquery as a webpack external in vue.config.js as follows:

...
configureWebpack: {
    externals: {
      jquery: 'jQuery'
    }
  }
...

and I load jquery from a CDN in a script tag in index.html. Obviously whenever I run vue-cli-service test:unit I get the following error since jquery isn't a dependency in the project:

 RUNTIME EXCEPTION  Exception occurred while loading your tests

ReferenceError: jQuery is not defined
    at Object.jquery (.../public/webpack:/external "jQuery":1:1)
...

I realize in my unit tests I should probably mock jquery somewhere, but I'm not sure what's the correct way to do this so I only do it in one place within the testing config.

Lance Whatley
  • 2,395
  • 1
  • 13
  • 16
  • another unanswered question with same problem: https://stackoverflow.com/questions/45724728/enzyme-unit-tests-with-webpack-externals – Lance Whatley Apr 12 '19 at 17:07
  • another unanswered question: https://stackoverflow.com/questions/46655678/how-to-test-a-webpack-bundle-that-has-external-dependencies – Lance Whatley Apr 12 '19 at 17:11

1 Answers1

0

Using Vue.js (as I see you've tagged your question thus), I created my own vue.config.js as is shown below.

Basically, it marks jquery as an external in development/production mode, and resolves it to a mocked version in test mode. Creating a mocked-up version of jquery I'll leave to you though. This example was adapted from a project that uses a different library.

const path = require('path');

module.exports = {
  configureWebpack() {
    const isTest = process.env.NODE_ENV === 'test';

    let resolve;
    let externals = { jquery: 'jquery ' };

    if (isTest) {
      externals = {};

      resolve = {
        alias: {
          // you may have to fiddle around with this path, from the point of view of where jquery is imported
          jquery: './tests/helpers/fakeJQuery.js',
        }
      };
    }

    return {
      resolve,
      externals,
    };
  },
};

Luke H
  • 3,125
  • 27
  • 31