如何使用Qunit对可观察对象使用节流阀的Knockout View模型进行单元测试 [英] 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时状态在true和false之间的切换,但是我无法超越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
之间切换的内容,我只需要订阅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对可观察对象使用节流阀的Knockout View模型进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!