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

Unit Testing window.location.assign using Karma/Mocha/Sinon/Chai

我正在尝试使用 Karma 作为我的测试 运行ner,Mocha 作为我的测试框架,Sinon 作为我的 mocking/stubbing/spying 库,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
    })
  }

如有任何想法,我们将不胜感激。

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

的讨论

看看这个截图,它可能会帮助你理解:

这意味着 sinon 无法监视 assign 函数,因为它无法覆盖其 属性 描述符。

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

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

然后在你的测试中,你可以做:

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

试试这个:

Object.defineProperty(window, 'location', {
    writable: true,
    value: {
        assign: () => {}
    }
});
sinon.spy(window.location, 'assign');