How to make raw JS be on top of bs.js file before imports?

I am trying to mock a class using Jest and I am using raw JS for that. But raw JS always comes after imports in bs.js file irrespective of its order in .res file. The import won’t be mocked if it is imported before jest mocks it. Utility is the class that needs to be mocked. The function getComponentJSONByID from Utility is imported inside VideoScrub module.

.res looks like this.

%raw(`jest.doMock('app/utilities/utility.ts', () => {
  return class Utility {
      static getComponentJSONByID(componentID) {
        return {
          duration: {
            absolute_start: 1.0,
            absolute_end: 6.2,
            absolute_duration: 5.2,
          },
        };
      }
    }
})`)

open Jest
open Expect
open VideoScrub

bs.js looks like this

var Jest = require("@glennsl/bs-jest/src/jest.bs.js");
var VideoScrub = require("./VideoScrub.bs.js");
var Caml_exceptions = require("bs-platform/lib/js/caml_exceptions.js");

((jest.doMock('app/utilities/utility.ts', () => {
  return class Utility {
      static getComponentJSONByID(componentID) {
        return {
          duration: {
            absolute_start: 1.0,
            absolute_end: 6.2,
            absolute_duration: 5.2,
          },
        };
      }
    }
})));

Any help on this would be appreciated.

I’m not seeing the import of the mocked class in this code snippet. Is this the full snippet?

My mistake. I should have mentioned that the function getComponentJSONByID from Utility is imported inside VideoScrub module. Have added this to the original post as well.

There is no way to put code above the generated import statements that I’m aware of. This falls into the same category as dynamic imports, which aren’t supported at the moment.

I don’t use Jest but I do have another scenario that breaks with built-in import style, the way I deal with it is to put my require in a raw block. Porting my example to Jest looks a bit like this:

type jest
let jest: jest = %raw(`require("@glennsl/bs-jest/src/jest.bs.js")`)

Unfortunately by doing this you lose the ability to use the Jest module directly (because that will generate a require at the top of the file), the only way to interact with it is using external bindings.

In your case, a dedicated module to add the mock in this way might work well enough.

1 Like