How can I mock the imports of an ES6 module?

后端 未结 8 1558
醉话见心
醉话见心 2020-11-28 21:33

I have the following ES6 modules:

File network.js

export function getDataFromServer() {
  return ...
}

File widget.js<

8条回答
  •  感情败类
    2020-11-28 21:45

    I've started employing the import * as obj style within my tests, which imports all exports from a module as properties of an object which can then be mocked. I find this to be a lot cleaner than using something like rewire or proxyquire or any similar technique. I've done this most often when needing to mock Redux actions, for example. Here's what I might use for your example above:

    import * as network from 'network.js';
    
    describe("widget", function() {
      it("should do stuff", function() {
        let getDataFromServer = spyOn(network, "getDataFromServer").andReturn("mockData")
        let widget = new Widget();
        expect(getDataFromServer).toHaveBeenCalledWith("dataForWidget");
        expect(otherStuff).toHaveHappened();
      });
    });
    

    If your function happens to be a default export, then import * as network from './network' would produce {default: getDataFromServer} and you can mock network.default.

提交回复
热议问题