ava测试失败通过添加console.log语句

时间:2018-06-29 11:11:08

标签: javascript ava

这是正在测试的功能:

const delimitedBinary = /^(?:[01]{8} ){3,}$/gm;
const nonDelimitedBinary = /^(?:[01]{8}){3,}$/gm;
const byteRegex = /[01]{8}/gm;

function decode(string) {
    string = string.trim();
    let bytes;

    if (delimitedBinary.test(string + ' ')) {
        bytes = (string + ' ').match(byteRegex);
    } else if(nonDelimitedBinary.test(string)) {
        bytes = string.match(byteRegex);
    }

    if (bytes) {
        return decodeBytes(bytes);
    }

    return '';
}

function decodeBytes(bytes) {
    return utf.getStringFromBytes(bytes.map(byte => parseInt(byte, 2)));
}

我在test/tests.js中进行了一些测试。这是摘录:

test('Decodes binary on separate line', t => {
    t.is(app.decode('text \n01110000 01100001 01110011 01110011'), 'pass');
});

test('Decodes emojis', t => {
    t.is(app.decode('11110000 10011111 10001110 10001001'), '');
});

第一次测试失败。在将console.log()添加到第一个测试中后,

test('Decodes binary on separate line', t => {
    console.log(app.decode('text \n01110000 01100001 01110011 01110011'));
    t.is(app.decode('text \n01110000 01100001 01110011 01110011'), 'pass');
});

第一个测试现在通过,第二个测试失败。在向第二项测试中添加console.log()语句后,

test('Decodes emojis', t => {
    console.log(app.decode('11110000 10011111 10001110 10001001'));
    t.is(app.decode('11110000 10011111 10001110 10001001'), '');
});

...两项测试均通过。

我确定我正在做一些愚蠢的事情,或者错过了很多时间。我浏览过ava的常见陷阱文档,找不到任何相关内容。

1 个答案:

答案 0 :(得分:2)

测试用例正常工作。问题是decode不是纯的,每次调用时它返回不同的结果,并且仅在第二次调用时返回正确的结果。因此,如果您之前添加console.log,则结果正确,否则为false:

console.log(
  decode('text \n01110000 01100001 01110011 01110011'),
  decode('text \n01110000 01100001 01110011 01110011')
);

但是为什么会这样呢?正如docs

中所述
  

与exec()(或与其结合使用)一样,在同一个全局正则表达式实例上多次调用的test()将前进到先前的匹配。

正则表达式是有状态的,只要您在其上调用.test()就会更改其状态,因此它会产生不同的结果。