AVA 测试问题

AVA testing problems

本文关键字:问题 测试 AVA      更新时间:2023-09-26

我正在尝试使用 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, '');
  });
});

分辨率是

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

但它说我的测试通过了。我一直在关注这个测试。这是我一直在看的片段

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();
    });
});

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

很抱歉造成混乱,不幸的是,您正在查看的单元测试使用 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();
    });
});

现在,看起来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();
        }
    });
});

最后,我鼓励你考虑实现一个基于承诺的 api,这样你就可以利用async函数和await关键字。它最终创建了比回调更干净的代码。如果要多次调用回调,请考虑可观察量。AVA 文档中记录了两者的测试策略。关于可观察量的更多信息很容易通过谷歌搜索找到。

感谢您尝试 AVA。继续提出这些问题!