如何在TypeScript中为测试使用模拟覆盖setInterval
背景:我正在尝试将mocha测试套件从JavaScript转换为TypeScript。该库在过去出现的一个问题是,它在Electron中会出错,因为它希望如何在TypeScript中为测试使用模拟覆盖setInterval,typescript,Typescript,背景:我正在尝试将mocha测试套件从JavaScript转换为TypeScript。该库在过去出现的一个问题是,它在Electron中会出错,因为它希望setInterval使用unref()方法返回一个对象,这在Node.js中是如此,但在Electron中不是这样。问题已经解决,并编写了测试 将全局setInterval()方法临时替换为仅返回数字的模拟方法,并验证库是否正常工作: describe("timeout", function() { const originalS
setInterval
使用unref()
方法返回一个对象,这在Node.js中是如此,但在Electron中不是这样。问题已经解决,并编写了测试
将全局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:无法分配给“setInterval”,因为它不是变量。
其中setInterval被覆盖,而它又被还原
是否有办法禁用此测试的错误,并使setInterval
可写