单元测试window.location.assign使用Karma / Mocha / Sinon / Chai

问题描述 投票:2回答:2

我试图使用Karma作为我的测试运行器,Mocha作为我的测试框架,Sinon作为我的模拟/存根/间谍库,以及Chai作为我的断言库来单元测试函数。我在我的Karma配置中使用Chromium作为我的无头浏览器。

但是,我完全感到困惑,为什么我收到以下错误:

TypeError: Cannot redefine property: assign

...当我对此运行npm测试时:

function routeToNewPlace() {  
  const newLoc = "/accountcenter/content/ac.html";
  window.location.assign(newLoc);
}
describe('tests', function() {
  before('blah', function() {
    beforeEach('test1', function() {
          window.onbeforeunload = () => '';
      });
    });
  it('routeToNewPlace should route to new place', function() {
    expectedPathname = "/accountcenter/content/ac.html";
    routeToNewPlace();
    const stub = sinon.stub(window.location, 'assign'); 
    assert.equal(true, stub.withArgs(expectedUrl).calledOnce);
    stub.restore();
  });
});

正如您所看到的,我正在尝试为window.location分配一个空字符串,但这似乎没有帮助。

这是我的karma.config.js:

module.exports = function(config) {
    config.set({
      frameworks: ['mocha', 'chai', 'sinon'],
      files: ['jstests/**/*.js'],
      reporters: ['progress'],
      port: 9876,  // karma web server port
      colors: true,
      logLevel: config.LOG_INFO,
      //browsers: ['Chrome', 'ChromeHeadless', 'MyHeadlessChrome'],
      browsers: ['ChromeHeadless'],
      customLaunchers: {
        MyHeadlessChrome: {
          base: 'ChromeHeadless',
          flags: ['--disable-translate', '--disable-extensions', '--remote-debugging-port=9223']
        }
      },
      autoWatch: false,
      // singleRun: false, // Karma captures browsers, runs the tests and exits
      concurrency: Infinity
    })
  }

任何想法将不胜感激。

unit-testing mocha karma-runner sinon chai
2个回答
2
投票

您看到的问题是window.location.assign是一个不可写且不可配置的本机函数。请参阅property descriptors on MDN的讨论。

请参阅此屏幕截图,它可能有助于您了解:

Showing property descriptor of window.location.assing

这意味着sinon不能监视assign函数,因为它不能覆盖它的属性描述符。

最简单的解决方案是将对window.location.assign的所有调用包装到您自己的方法中,如下所示:

function assignLocation(url) {
  window.location.assign(url);
}

然后在测试中,您可以:

const stub = sinon.stub(window, 'assignLocation');

0
投票

试试这个:

Object.defineProperty(window, 'location', {
    writable: true,
    value: {
        assign: () => {}
    }
});
sinon.spy(window.location, 'assign');
© www.soinside.com 2019 - 2024. All rights reserved.