【问题标题】:Changing window.location.href in Mocha/Karma stack在 Mocha/Karma 堆栈中更改 window.location.href
【发布时间】:2017-12-12 15:59:43
【问题描述】:

我在我的测试环境中使用 Karma/Mocha。我有 js 文件,它依赖于 window.location.href 来获取 url。当我使用 Karma 运行测试时,默认 url 是 www.localhost:3123/context.html。是否可以更改 url/add 参数或告诉 karma 为这个特定的测试套件使用自定义 url?

//JS file has
function populate(){
   var url = new URL(window.location.href);
   -- check if the url have parameter, lets say carInfo
   -- if has then dispatches an event
}

//Mocha test
describe('...', function() {
    it ('...', function() {
       -- call populate()
       -- listen if the event was triggered
    })
})

【问题讨论】:

    标签: javascript unit-testing mocha.js karma-runner


    【解决方案1】:

    一般来说,尝试在您的代码中分离依赖项,以便您能够在测试中交换这些依赖项。这背后的概念称为控制反转。您也可以考虑考虑依赖注入

    在您的具体情况下,window.location.href 是特定于特殊环境(浏览器)的依赖项,在 node.js 或其他东西中运行测试时不存在该依赖项

    function populate(url){
       // trigger the event...
    }
    
    describe('...', function() {
       it ('...', function() {
          populate(new URL("http://...")
          // listen if the event was triggered
       })
    

    })

    【讨论】:

      猜你喜欢
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2021-06-15
      • 2016-08-12
      • 1970-01-01
      • 2013-07-26
      相关资源
      最近更新 更多