简体   繁体   中英

How does this Jasmine test code work?

I'm reading Node Craftsman by Manuel Kiessling and in the chapter on event emitters he provides the following Jasmine test spec

it('should fire a "grew" event when the file grew in size', function(done) {
    var path = '/var/tmp/filesizewatcher.test';
    exec('rm -f ' + path + ' ; touch ' + path, function() {
        watcher = new FilesizeWatcher(path);
        watcher.on('grew', function(gain) {
            expect(gain).toBe(5);
            done();
        });
        exec('echo "test" > ' + path, function() {});
    });
});

I understand that we have to trigger done() to tell Jasmine the event has indeed fired and execute the callback registered with it()

What I don't understand is, how is that code reached when the exec statement needed to trigger the watcher grew event is inside another callback that depends on done being executed. I tried moving the exec outside the inner callback and the test times out, I don't understand why. Don't we need this part to be synchronous for anything to actually start happening ?

Help me free my mind of its procedural shackles! I'm so confused that my question seems confusing even to me.

Ok I had this all backwards, I was confused by the author's explanation.

Jasmine uses expect and matchers to assess whether or not the test passes and therefore that it finished. Testing async functions like event emitters requires us to let Jasmine know when the test has actually finished, hence the need for done() . The Jasmine callback to it() in that case isn't needed to start but to finish executing the spec.

From the Jasmine docs :

And this spec will not complete until its done is called.

By default jasmine will wait for 5 seconds for an asynchronous spec to finish before causing a timeout failure. If the timeout expires before done is called, the current spec will be marked as failed and suite execution will continue as if done was called.

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