Jasmine 2.0 中对异步测试的更改在很多方面都很棒。但是,当我无法将回调绑定(bind)到异步方法时,我不确定我是否完全理解如何测试异步代码。
如何在 Jasmine 2.0 中针对未知数量的异步事件进行测试?或不提供回调调用的并行异步事件。
在 1.3 中我会这样做:
describe("my spec", function () {
it("should check the state of a variable after unknown number of async events", function () {
// This will execute several async functions in parallel (more than 1).
// Once they are all complete the 'window.done' variable will be set to "true".
// This method does not provide a callback.
fire_parallel_async_methods();
waitsFor(function () {
// I know that once this condition is met,
// all the above async calls are done
return window.done === true;
});
runs(function () {
// Now I can run the rest of my unit tests
});
});
});
Tony 的答案是 Jasmine 2.0: refactoring out 1.3's runs() and waitsFor()唯一的解决方案?
另一个用例是事件验证。例如:
describe("my spec", function () {
it("should make sure event is fired", function () {
// This element has an event binding on 'click' which changes its class.
// In this test I want to check to make sure the event does the right thing.
var $element = $('.some-element');
// Simulate a click
$element.simulate('click');
// or $element.click();
waitsFor(function () {
// Once the event is done, the element should have a new 'after-event' class
return $element.hasClass('after-event');
});
});
});
在此示例中,我无法访问事件的绑定(bind),因此无法将回调附加到它。我将如何在 Jasmine 2.0 中验证这一点?
最佳答案
我能够找到使用超时的解决方法,它模仿 waitsFor() 行为:
describe("my spec", function () {
it("should make sure event is fired", function (done) {
// This element has an event binding on 'click' which changes its class.
// In this test I want to check to make sure the event does the right thing.
var $element = $('.some-element');
// Simulate a click
$element.simulate('click');
// or $element.click();
// Set a timeout to wait for the async event to go through.
// Pick a time here that will be enough. It's a little messy, but it works for cases
// where you can't attach a callback. The hardest part is figuring out how long to set
// the timeout for.
setTimeout(function () {
// Do your test here
expect($element).toHaveClass('after-event');
// Tell Jasmine the test is finished
done();
}, 500);
});
});
关于javascript - Jasmine 2.0 无法设置回调时的异步测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23788809/