SpyOn individually exported ES6 functions

前端 未结 2 1106
囚心锁ツ
囚心锁ツ 2021-01-17 19:05

tl;dr:

  1. I use Jasmine;
  2. I want to test aaa function which called bbb from the same module; <
2条回答
  •  日久生厌
    2021-01-17 19:51

    The code wasn't written with testing concerns in mind, it won't get full coverage without refactoring.

    It's impossible to force aaa to call the spy in this case. It refers directly to bbb function in module scope. There's no object to spy on.

    It's basically the same sort of JavaScript scope problem as:

    (() => {
      var bar = 1; // there's no way to reach this variable from the outside
    })();
    

    It is possible to do that if functions are consistently referred as object properties. There's no such object in ES modules but this recipe is common in CommonJS modules, especially because of testability concerns (bundling tools like Webpack support both):

    exports.aaa = function aaa() {
      return exports.bbb();
    }
    
    exports.bbb = function bbb() {
      return 222;
    }
    

    This way bbb property could be spied on * import with spyOn(util, 'bbb'), as shown in original code. This doesn't apply to native ES modules that have read-only exports and don't interoperate with CommonJS modules.

    It may be easier to do that if aaa and bbb reside in different modules. This way there's a possibility to mock modules (this doesn't apply to native ES modules).

提交回复
热议问题