在Mocha / Karma堆栈中更改window.location.href

时间:2017-12-12 15:59:44

标签: javascript unit-testing mocha karma-runner

我在我的测试环境中使用Karma / Mocha。我有js文件,它取决于window.location.href来获取url。当我使用Karma运行测试时,默认URL是www.localhost:3123 / context.html。是否可以更改url / add paramaters或者说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
    })
})

1 个答案:

答案 0 :(得分: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
   })

})