【发布时间】:2019-02-03 17:29:42
【问题描述】:
我正在尝试使用 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
})
}
任何想法将不胜感激。
【问题讨论】:
-
编辑添加我正在使用 Chromium 无头浏览器,并提供我的 karma.config.js。
-
在
const stub = sinon.stub(window.location, 'assign');中使用spy代替stub怎么样?
标签: unit-testing mocha.js karma-runner sinon chai