背景:我正在尝试将Mocha测试套件从JavaScript转换为TypeScript。过去,该库发生的一个问题是它会在Electron中出错,因为它希望setInterval
使用unref()
方法返回一个对象,在Node.js中就是这种情况,但在电子。该问题已解决,并编写了测试。
The test临时用一个仅返回数字的模拟方法替换全局setInterval()
方法,并验证该库的行为是否正确:
describe("timeout", function() {
const originalSetInterval = setInterval;
let timeoutId = 1;
let realTimeoutId: Timeout;
beforeEach(function() {
timeoutId = 1;
// eslint-disable-next-line no-global-assign
setInterval = function(callback: () => any, timeout: number) {
realTimeoutId = originalSetInterval(callback, timeout);
return timeoutId++;
};
});
it("can run in electron where setInterval does not return a Timeout object with an unset function", function(done) {
const store = new MemoryStore(-1);
const key = "test-store";
store.incr(key, function(err, value) {
if (err) {
done(err);
} else {
if (value === 1) {
done();
} else {
done(new Error("incr did not set the key on the store to 1"));
}
}
});
});
afterEach(function() {
// eslint-disable-next-line no-global-assign
setInterval = originalSetInterval;
clearTimeout(realTimeoutId);
});
});
TypeScript抛出错误TS2539: Cannot assign to 'setInterval' because it is not a variable.
,其中setInterval被覆盖,再次被恢复。
是否有一种方法可以为此测试禁用该错误并使setInterval
可写?