3

I am trying to write a test using AVA but I can't seem to get it to work write. fn passes the callback function through all of my functions and calls it once it's done everything. My test is

import test from 'ava';
import fn from './index.js';

test('NonLiteral && Literal', function (t) {
  fn('test.txt', '', function (res) {
    console.log(res);
    t.is(res, '');
  });
});

The res is

This is a test
How is it going
So far!!!

but it is saying that my test is passing. I've been following this test. Here is the snippet I've been looking at

test('throwing a named function will report the to the console', function (t) {
    execCli('fixture/throw-named-function.js', function (err, stdout, stderr) {
        t.ok(err);
        t.match(stderr, /\[Function: fooFn]/);
        // TODO(jamestalmage)
        // t.ok(/1 uncaught exception[^s]/.test(stdout));
        t.end();
    });
});

Can someone explain to me what I am doing wrong?

4

1 回答 1

6

Sorry for the confusion, unfortunately that unit test you are looking at uses tap, not AVA. (AVA does not use itself for testing ... yet).

I am guessing that fn is async. In that case, you probably want to use test.cb.

test.cb('NonLiteral && Literal', function (t) {
    fn('test.txt', '', function (res) {
        console.log(res);
        t.is(res, '');
        t.end();
    });
});

Now, it looks like maybe fn will call that callback more than once, but it is an error to call t.end() more than once. If that is so, you will need to do something like this:

test.cb('NonLiteral && Literal', function (t) {
    var expected = ['foo', 'bar', 'baz'];
    var i = 0;
    fn('test.txt', '', function (res) {
        t.is(res, expected[i]);
        i++;
        if (i >= expected.length) {
            t.end();
        }
    });
});

Finally, I would encourage you to consider implementing a Promise based api so you can take advantage of async functions and the await keyword. It ends up creating much cleaner code than callbacks. In situations where you want to call a callback multiple times, consider Observables. Testing strategies for both are documented in the AVA docs. Further info on Observables is pretty easy to find by Googling.

Thanks for trying AVA. Keep those questions coming!

于 2016-03-10T21:11:25.120 回答