【问题标题】:Jest - Unit Testing a Namespaced FileJest - 对命名空间文件进行单元测试
【发布时间】:2021-09-18 22:30:10
【问题描述】:

是否可以使用 Jest 为使用以下格式命名空间的 JavaScript 文件编写单元测试?

// utilities.js

var MyApp = MyApp || {};
MyApp.Common = MyApp.Common || {};
MyApp.Common.Utilities = new function(){
    this.getSomething = function(){  // Need to unit test this function
        return 'Something';
    }
}

如果没有,是否有更好的方法来构建命名空间以进行单元测试?

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

    如果你像下面的例子那样导出 MyApp,那么你可以在 utility.test.js 中

    const {MyApp} = require('./utilities');
    
    it('should work', ()=>{
      expect(MyApp.Common.Utilities.getSomething()).toEqual('something');
    });
    
    

    【讨论】:

    • 是否仍然可以将模拟/依赖注入与这样的静态函数一起使用?我使用的函数引用了 jQuery,即使在 Jest 设置中定义了全局变量,Jest 测试也会失败。
    • 您可以使用 Jest 模拟整个模块。这个答案可能就是你要找的。 stackoverflow.com/a/64600296/927687
    猜你喜欢
    • 2011-10-16
    • 1970-01-01
    • 2012-09-21
    • 2019-05-16
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    相关资源
    最近更新 更多