如何使用 Qunit 进行单元测试一个在可观察量上使用节流阀的淘汰赛视图模型 [英] How to Unit Test with Qunit a Knockout View Model that uses throttle on observables
问题描述
假设这是我的视图模型
function VM()
{
var self = this;
this.Status = ko.observable(false);
this.A = ko.observable();
this.B = ko.computed(
function()
{
return self.A();
}
).extend( throttle: 200 );
this.B.subscribe(
function()
{
self.Status(true);
setTimeout( //ajax simulation
function(){
self.Status(false);
}
,200)
}
);
}
我想要一个测试来验证状态在设置 A 时是否在真和假之间切换,但我无法克服 VM 的双重异步特性.有没有办法通过多次 stop()/start() 调用来测试这个?
I want a test that verifies status toggles between true and false as A is set but i can't get past the dual async nature of the VM. Is there a way to test this with multiple stop()/start() calls?
推荐答案
如果你只测试什么Status
在true
和false
之间切换code> 我只想订阅 Status
更改并检查第一次获得值 true
和第二次获得值 false<的更改回调/代码>.
If you only what to test that the Status
toggles between true
and false
I would just subscribe on the Status
change and check in the change callback that the first time I get the value true
and the second time the value false
.
以这种方式编写测试,您需要有一对启动/停止对,如下所示:
Writing your test this way you would need to have one start/stop pair, something like this:
asyncTest("computed with ajax", function () {
expect(2); // expecting two asserts, so the Status only changes twice
var sut = new VM();
// multiple calls to A to test the throttle behavior
sut.A('something');
sut.A('something2');
sut.A('something3');
stop();
var callCount = 0;
var expectedValues = [true, false];
sut.Status.subscribe(function (value) {
start();
equal(sut.Status(), expectedValues[callCount]);
callCount++;
});
});
演示 JSFiddle.
这篇关于如何使用 Qunit 进行单元测试一个在可观察量上使用节流阀的淘汰赛视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!