gpt4 book ai didi

javascript - 失败的测试通过添加 console.log 语句

转载 作者:行者123 更新时间:2023-11-29 20:52:33 24 4
gpt4 key购买 nike

这是被测试的函数:

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 不是纯粹的,每次调用它都会返回不同的结果,并且只有在第二次调用时才返回正确的结果。所以如果之前加个console.log,结果是对的,否则就是false:

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

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

As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.

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

关于javascript - 失败的测试通过添加 console.log 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51100427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com