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

Javascript 更改Mocha/Karma堆栈中的window.location.href,javascript,unit-testing,mocha.js,karma-runner,Javascript,Unit Testing,Mocha.js,Karma Runner,我正在使用Karma/Mocha作为我的测试环境。我有一个js文件,它依赖于window.location.href来获取url。当我使用Karma运行测试时,默认url是www.localhost:3123/context.html。是否可以更改url/添加参数,或者对karma说,为这个特定的测试套件使用自定义url //JS file has function populate(){ var url = new URL(window.location.href); -- che

我正在使用Karma/Mocha作为我的测试环境。我有一个js文件,它依赖于window.location.href来获取url。当我使用Karma运行测试时,默认url是www.localhost:3123/context.html。是否可以更改url/添加参数,或者对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
    })
})

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

在您的具体案例中,
window.location.href
是一个特定于特定环境的依赖项,即浏览器,在node.js或其他文件中运行测试时不存在该依赖项

i、 e

})

function populate(url){
   // trigger the event...
}

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