简体   繁体   中英

Asynchronous test cases with nodeunit

I want to test many methods one after the other with one methods output has to be passed to next method.

For Example : I have 2 methods to test, called add and delete. add method's onsuccess will return added object(with its id). same object i want to pass to delete method so that created object gets deleted.

exports.add = function(test) {
    nodemanager.add({
        name : 'my name'
    }, function(node) {
        //this is onsuccess callback.
        test.ok(node && node.id, 'Failed to get added node\'s info');
        test.done();
    });
}

exports.del = function(test) {
    //Here i need to pass node object returned from onsuccess on add method.
    nodemanager.del(node, function(node) {
        test.ok(node, 'Deleted node is null');
        test.done()
    });
}

One way is, defining node object outside of these 2 functions and access from both the methods.

I was just wondering if this is the proper way or is there a better approach.

It is common practice to isolate tests from each other. There are test suites that run tests in random order to make sure that users don't rely on any order.

So if your second test checks that an added node can be deleted, it should ensure that this element is available. Probably something like this:

exports.add = function(test) {
    nodemanager.add({
        name : 'my name'
    }, function(node) {
        test.ok(node && node.id, 'Failed to get added node\'s info');
        test.done();
    });
}

exports.del = function(test) {
    nodemanager.add({
        name : 'my name'
    }, function(addedNode) {
        nodemanager.del(addedNode, function(deletedNode) {
            test.ok(deletedNode, 'Deleted node is null');
            test.done()
        });
    });
}

Of course this solution has another problem: If nodemanager.add breaks your del test will fail, too. However, I think that's acceptable here, if it is hard to mock the add behavior here.

If you're currently using this nodeunit, https://github.com/caolan/nodeunit , as I assume you are definitely check out the author's other project Async ( https://github.com/caolan/async ). I think the Waterfall function is what you're looking for. I was looking for a similar answer, which led me to this page so Im about to try it out and will let you know how it goes.

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