[英]jasmine unit test for javascript CustomEvent
How do I test that a CustomEvent is dispatched in jasmine? 如何测试茉莉花中调度了CustomEvent? When I try running the following code I get the error: "ReferenceError: Can't find variable: CustomEvent". 当我尝试运行以下代码时,出现错误:“ ReferenceError:找不到变量:CustomEvent”。
function testCustomEvent() {
window.dispatchEvent(new CustomEvent('myCustomEvent', {
detail: 'foo'
}));
}
describe('testCustomEvent', function() {
it('dispatches myCustomEvent', function() {
var eventSpy = jasmine.createSpy();
window.addEventListener('myCustomEvent', eventSpy);
testCustomEvent();
expect(eventSpy).toHaveBeenCalledWith('foo');
});
});
The expectation is not met because eventSpy is called with { detail: 'foo'}
无法满足期望,因为使用{ detail: 'foo'}
调用了eventSpy
Also, the arguments passed is a new event object containing values of the parameter sent to the Event constructor. 同样,传递的参数是一个新的事件对象,其中包含发送到Event构造函数的参数值。 So it's never the same object. 因此,它绝不是同一对象。 You will have to enforce a deep partial equal by using a partial matcher if you're using Jasmine 2.0 如果您使用的是Jasmine 2.0,则必须通过使用部分匹配器来强制执行深度比较相等的操作
expect(eventSpy).toHaveBeenCalledWith(jasmine.objectContaining({
detail: 'foo'
}));
Or have a headache if you're using a version below 2.0 如果您使用的版本低于2.0,或者感到头疼
I think the only problem with your code is: 我认为您的代码唯一的问题是:
You are using toHaveBeenCalledWith
method instead of toHaveBeenCalled
. 您正在使用toHaveBeenCalledWith
方法,而不是toHaveBeenCalled
。
Former is used for checking two things: 前者用于检查两件事:
Try to run your code here - Try Jasmine . 尝试在此处运行代码-尝试使用Jasmine 。 After replacing toHaveBeenCalledWith
with toHaveBeenCalled
. 将toHaveBeenCalledWith
替换为toHaveBeenCalledWith
toHaveBeenCalled
。
Note, do not pass any argument to latter. 请注意,请勿将任何参数传递给后者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.