How to test an ES6 class that needs jquery?

前端 未结 4 1895
轻奢々
轻奢々 2020-11-30 15:56

I have an ES6 module that needs jquery.

import $ from \'jquery\';

export class Weather {
    /**
     * Constructor for Weather class
     *
     * @param          


        
4条回答
  •  感情败类
    2020-11-30 16:21

    I ran into a similar problem recently. I found that when I ran a test with mocha and webpack, there was no 'window' in the scope for jquery to bind to and as a result it was undefined. To solve this problem, I found that I could follow this advice and replace import * as $ from jquery in the source file with:

    // not the winning solution
    const jsdom = require("jsdom");
    const { window } = new jsdom.JSDOM();
    const $ = require('jquery')(window);
    

    But then the source file would no longer properly bundle with webpack, so I gave up on using mocha and babel for client-side javascript tests. Instead, I found that I could test my client-side code properly using a combination of karma and phantomjs.

    First, I installed all the dependencies:

    npm install -D babel-loader @babel/core
    npm install -D mocha chai sinon mocha-webpack
    npm install -D phantomjs-prebuilt
    npm install -D webpack
    npm install -D karma karma-mocha karma-chai karma-sinon 
    npm install -D karma-mocha-reporter karma-phantomjs-launcher karma-webpack
    

    Then I setup a config file in the root called karma.config.js with:

    module.exports = function(config) {
      config.set({
        browsers: ['PhantomJS'],
        files: [
          './test/spec/*.js'
        ],
        frameworks: ['mocha', 'chai', 'sinon'],
        reporters: ['mocha'],
        preprocessors: {
          './test/spec/*.js': ['webpack']
        },
        webpack: {
          module: {
            rules: [
              { test: /\.js/, exclude: /node_modules/, loader: 'babel-loader' }
            ]
          },
          watch: true,
          mode: 'none'
        },
        webpackServer: {
          noInfo: true
        },
        singleRun: true
      });
    };
    

    Finally, I added "test": "karma start karma.config.js" to scripts in package.json. All the spec tests can now be run with npm test.

提交回复
热议问题