Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

knockout.js - How to Unit Test with Qunit a Knockout View Model that uses throttle on observables

Supposed this is my view model

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)
        }
    );

}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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++;
    });
});

Demo JSFiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...