更新时间:2022-05-07 23:33:03
我已经开始使用 import * as obj 样式,该样式将从模块中导入所有导出作为对象的属性,然后可以对其进行模拟。我发现这比使用诸如rewire或proxyquire或任何类似技术之类的方法要干净得多。例如,在需要模拟Redux操作时,我经常这样做。在上面的示例中,我可能会使用以下示例:
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();
});
});
如果您的函数恰好是默认导出,则 import * as network从'./network'
会产生 {default:getDataFromServer}
,您可以模拟network.default。
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.