这是我的班级:
class Clock {
// Runs callback while it continues
// to returns truthy values
constructor(callback, delay) {
this.callback = callback;
this.delay = delay;
this.timerId = null;
}
start() {
this.timerId = setTimeout(() => {
if (this.callback.call()) this.start();
}, this.delay);
}
// Want to kill some time?
kill() {
clearTimeout(this.timerId);
}
}
export default Clock;
相关测试:
import Clock from '../../src/js/lib/clock.js';
describe("Clock", function() {
it("Has a callback and a delay", function() {
let clock = ClockFactory();
expect(clock.callback).toBeDefined();
expect(clock.delay).toBeDefined();
});
describe("Is a clock", function() {
let observer,
clock;
beforeEach(function() {
jasmine.clock().install();
observer = { callback: function() {} };
spyOn(observer, 'callback')
console.log(observer)
clock = ClockFactory({callback: observer});
});
afterEach(function() {
jasmine.clock().uninstall();
clock.kill()
});
it("It periodically executes a callback", function() {
clock.start()
expect(observer.callback).not.toHaveBeenCalled();
jasmine.clock().tick(5001);
expect(observer.callback.calls.count()).toEqual(1);
jasmine.clock().tick(2500);
expect(observer.callback.calls.count()).toEqual(1);
jasmine.clock().tick(2500);
expect(observer.callback.calls.count()).toEqual(2);
});
it("It can stop ticking", function() {
clock.start()
expect(observer.callback).not.toHaveBeenCalled();
jasmine.clock().tick(5001);
expect(observer.callback.calls.count()).toEqual(1);
clock.kill()
jasmine.clock().tick(5000);
expect(observer.callback.calls.count()).toEqual(1);
});
});
function ClockFactory(options = {}) {
return new Clock(
(options.callback || function() {}),
options.delay || 5000
);
}
});
现在,当我运行测试时,我会遇到以下故障:
Failures:
1) Clock Is a clock It periodically executes a callback
Message:
TypeError: _this.callback.call is not a function
Stack:
TypeError: _this.callback.call is not a function
at clock.js:14:25
at Object.<anonymous> (clock_spec.js:34:23)
2) Clock Is a clock It can stop ticking
Message:
TypeError: _this.callback.call is not a function
Stack:
TypeError: _this.callback.call is not a function
at clock.js:14:25
at Object.<anonymous> (clock_spec.js:48:23)
我认为我根据示例正确使用间谍,但显然存在问题!有什么建议吗?
答案 0 :(得分:1)
您的Clock
构造函数需要一个函数(或至少一个带有call()
方法的对象)作为其第一个参数。在您的测试中,您正在调用ClockFactory
,如
observer = { callback: function () {} };
spyOn(observer, 'callback');
clock = ClockFactory({ callback: observer });
即。传递给ClockFactory
的第一个参数是
{ callback: { callback: function () {} } }
这很可能不是您的意图(除非您的ClockFactory
签名与您的Clock
构造函数签名不匹配)。尝试做类似
observer = jasmine.createSpy('observer');
clock = ClockFactory(observer);
或者,您可以使用&#34;选项对象&#34;您的Clock
构造函数中的模式,并编写类似
constructor({callback, delay}) {
this.callback = callback;
this.delay = delay;
...
}
然后,您可以传递包含callback
和delay
属性的单个对象,例如
observer = { callback: function () {} };
spyOn(observer, 'callback');
clock = ClockFactory(observer);