[Vuejs]-Can't import javascript file in vue test utils

0👍

What you’re really trying to do is import a Web Worker, not just any JavaScript file, and these only work in the browser.

You might try jsdom-worker, which emulates workers for Node, but I couldn’t make it work with Webpack, so if you’re using Webpack and its worker-loader plugin, you might want to mock the worker altogether for the test.

First separate your functionality out of the worker file into unlockWallet.js:

import { Wallet, Configs } from '@/helpers';

function create(password) {
  const createdWallet = {};
  const wallet = new Wallet.generate();
  createdWallet.walletJson = wallet.toV3(password, {
    kdf: Configs.wallet.kdf,
    n: Configs.wallet.n
  });
  createdWallet.name = wallet.getV3Filename();
  return createdWallet;
}

export default function(eventData) {
  if (eventData.type === 'createWallet') {
    const workerResult = create(eventData.data[0]);
    postMessage(workerResult);
  }
};

Then your worker will just import it. unlockWallet.worker.js:

import workerFunction from "./unlockWallet.js";

self.onmessage = async function (event) {
  self.postMessage(workerFunction(event.data));
};

This way you can mock the worker. test/mocks/unlockWallet.worker.js:

import workerFunction from "../../src/unlockWallet.js"; // or wherever you keep it

export default class Worker {
  constructor() {
    // should be overwritten by client code
    this.onmessage = () => { };
  }

  // mock expects data: { } instead of e: { data: { } }
  postMessage(data) {
    // actual worker implementation wraps argument arg into { data: arg },
    // so the mock needs to fake it 
    this.onmessage({ data: workerFunction (data) });
  }
}

Note that you should set onmessage before calling postMessage. For a real worker, this won’t matter because it’s called asynchronously, but our mock is synchronous, therefore in PasswordModal.vue it should be:

 worker.onmessage = function(e) {
   // ...
 };
 worker.postMessage({
    type: 'unlockWallet',
    data: [this.file, this.password]
  });

Related Resolving imports using webpack's worker-loader in Jest tests.

Leave a comment