How can I state in the QUnit test case that a particular baseline event was noted?
The application uses Backbone.js events (Backbone.js version 1.3.3) to communicate between the components. A simple view responds to a button click by triggering a custom event on the event bus:
const WheelView = Backbone.View.extend({
events: {
"click #btn-spin-wheel": "onSpinButtonClick",
},
onSpinButtonClick: function () {
console.log("DEBUG: clicked #btn-spin-wheel");
Backbone.trigger("wheel:spin");
},
});
I want a QUnit test case (QUnit version 1.22.0) that states "when this button is selected, the event" foo "appears on the event bus."
In the test case, you will also need to find out other aspects of the event (for example, optional arguments), so I need the function defined in the test case so that the test case runs as a callback for a specific event.
, , spy Sinon ( 1.9.0) :
QUnit.module("Button "btn-spin-wheel"", {
beforeEach: function (assert) {
this.wheelView = new WheelView();
},
afterEach: function (assert) {
delete this.wheelView;
},
});
QUnit.test(
"Should observe the "wheel:spin" event.",
function (assert) {
assert.expect(1);
const spinWheelButton = document.querySelector(
"#qunit-fixture #btn-spin-wheel");
const eventListener = sinon.spy(function () {
console.log("DEBUG:QUnit: received ‘wheel:spin’ event");
});
Backbone.once("wheel:spin", eventListener);
const done = assert.async();
window.setTimeout(function () {
spinWheelButton.click();
window.setTimeout(function () {
assert.ok(eventListener.calledOnce);
}.bind(this));
done();
}.bind(this), 500);
});
console.log
, , . :
DEBUG: clicked #btn-spin-wheel
DEBUG:QUnit: received ‘wheel:spin’ event
:
DEBUG: clicked #btn-spin-wheel
, :
Button "btn-spin-wheel": Should observe the "wheel:spin" event. (3, 0, 3) 579 ms
1. Assertion after the final `assert.async` was resolved @ 578 ms
Source: Assert.prototype.ok@file:///usr/share/javascript/qunit/qunit.js:1481:3
2. failed, expected argument to be truthy, was: false @ 578 ms
Expected: true
Result: false
Source: @file://[…]/test-foo.html:50:29
3. Expected 1 assertions, but 2 were run @ 579 ms
Source: @file://[…]/test-foo.html:36:13
Source: @file://[…]/test-foo.html:36:13
QUnit , assert.async
setTimeout
, . .
QUnit, Sinon Backbone, ( ) ?