我似乎无法使我的测试工作。我有一个简单的混音,这样:
export const mixin = superclass => class mixin extends superclass {
constructor() {
super();
this.addEventListener('do-it', this.doIt);
}
doIt() {
console.log('did it');
}
};
还有一个简单的测试:
describe('mixin', () => {
it('should call doIt', () => {
class TestElement extends mixin(HTMLElement) {}
customElements.define('test-element', TestElement);
const el = new TestElement();
const spy = sinon.spy(el, 'doIt');
el.dispatchEvent(new CustomEvent('do-it'));
expect(spy.callCount).to.equal(1);
});
});
https://jsfiddle.net/nbulhvkd/
它记录了did it
,但间谍的callCount
值为0
。如果我做const spy = sinon.spy(console, 'log');
,间谍的callCount
是1
。例如,间谍方法的正确方法是什么?
您的'dispatchevent'调用可能是异步的,因此呼叫的量确实为0,因为它是同步执行的。否则您的语法是好的 - 正如您在控制台调用的测试所证明的那样。
我使用TestElement.prototype
进行间谍活动,并在实例化new TestElement();
之前将其移动。现在有效,但有人可以解释为什么吗?
describe('Sinon examples', () => {
it('logs test on do-it', () => {
class TestElement extends mixin(HTMLElement) {}
customElements.define('test-element', TestElement);
const spy = sinon.spy(TestElement.prototype, 'doIt');
const el = new TestElement();
el.dispatchEvent(new CustomEvent('do-it'));
expect(spy.calledOnce).to.be.true;
});
});
https://jsfiddle.net/h0f9le16/