简体   繁体   中英

Resetting a KnockoutJS ViewModel in QUnit Tests

I'm just getting started with Knockout JS and with QUnit for doing unit tests of my knockout view model. The problem that I'm running into is that if I have multiple tests in my qunit test javascript file, and I link to a javascript file which includes my View Model definition... any changes that I make to the View Model in one test are also present when I start the next test in the test module. I'm used to have an NUnit environment where my state is cleared automatically between tests.

Is there a method, pattern or example that someone can point to which shows the best way to define a view model, and have it reset it's state for the start of each unit test?

Are you using the second parameter (lifecycle) of module ? If not, you should be able to instantiate your view model at this level, something like:

module("foo", {
    setup: function() {
        this.model = instantiateModel();
    },
    tearDown: function() {
        // execute reset here
    });

test("bar", function() {
    ok(this.model.hasSomething() !== null, "msg");
});

From what I remember reading, QUnit tets are run in the same scope as setup and tearDown , so any members defined in setup will be accessible within any subsequent tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM