AVA测试问题

Sir*_*lot 3 javascript testing node.js ava

我正在尝试使用AVA编写测试,但我似乎无法让它工作写.fn通过我的所有函数传递回调函数,并在完成所有操作后调用它.我的考试是

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, '');
  });
});
Run Code Online (Sandbox Code Playgroud)

res是

This is a test
How is it going
So far!!!
Run Code Online (Sandbox Code Playgroud)

但它说我的测试正在通过.我一直在关注这个测试.这是我一直在关注的片段

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();
    });
});
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释我做错了什么吗?

Jam*_*age 6

很抱歉让您感到困惑,不幸的是您正在使用单元测试tap,而不是AVA.(AVA不会将自己用于测试......).

我猜这fn是异步的.在这种情况下,您可能想要使用test.cb.

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

现在,它似乎可能fn不止一次地调用该回调,但是多次调用是错误的t.end().如果是这样,你需要做这样的事情:

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();
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

最后,我鼓励您考虑实现基于Promise的API,以便您可以利用async函数和await关键字.它最终会创建比回调更清晰的代码.在您想多次调用回调的情况下,请考虑Observables.两者的测试策略都记录在AVA文档中.Googling很容易找到关于Observables的更多信息.

感谢您尝试AVA.保持这些问题!