Loading a WASM in Jest

187 Views Asked by At

I am using libsvm.js to use some Python trained models in the browser. This is working well both in node and in the browser. There is a wasm file used by libsvm.js that needs to be loaded. I cannot get it to load in Jest.

Jest... which thinks it is a browser, doesn't have access to the libsvm.wasm file which is in the public folder of a Reactjs app. This loads in the browser, but Jest is different and i don't fully understand this.

The wasm location is handled in pre.js in the src folder. (https://github.com/mljs/libsvm/blob/master/src/pre.js)

In node, libsvm.wasm is loaded using two different methods this is the one used for Browser and Jest.

  function getCurrentPathBrowser() {
    if (
      typeof WorkerGlobalScope !== 'undefined' &&
      self instanceof WorkerGlobalScope
    ) {
      return self.location.href;
    }
    var sc = document.getElementsByTagName('script');

    for (var idx = 0; idx < sc.length; idx++) {
      var s = sc.item(idx);
      
      //THESE COMMENTS ARE ADDING BY OP
      //There is a script tag in index.html that matches
      //This tells libsvm-js to pick up the libsvm.wasm from 
      //localhost:3000/libsvm.wasm
      if (s.src && s.src.match(/libsvm\.js$/)) {
        return s.src;
      }
    }
    return window.location.href;
  }

When using the browser, there is a script tag that points to the public folder in react where i have libsvm.js and libsvm.wasm. This allows libsvm-js (which is actually a node module) looks for a script tag, it will find libsvm.wasm no matter which route the browser is currently viewing. i.e. localhost:3000/libsvm.wasm vs localhost:3000/some-path/libsvm.wasm

Now, when using Jest, there is no real localhost or file serving.

What is the best approach here to make a file available in Jest? Currently, libsvm is looking for http://localhost/libsvm.wasm (Notice no port) which is the same as the browser instance.

I've done some further exploring and looked into mocking the above function to return a 'correct' url for Jest. However, getCurrentPathBrowser is not exported by libsvm.js so i don't think it can be mocked.

0

There are 0 best solutions below