失败的测试通过添加控制台.log语句



这是正在测试的函数:

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 的常见陷阱文档,找不到任何相关内容。

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

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

但为什么会这样呢?正如文档中所述

与 exec(((或与它结合使用(一样,在同一全局正则表达式实例上多次调用的 test(( 将超越前一个匹配项。

正则表达式是有状态的,每当调用.test()时都会更改其状态,因此会产生不同的结果。

相关内容

最新更新