简体   繁体   中英

Failing tests pass on adding console.log statement

Here's the function being tested:

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

I have some tests in test/tests.js . Here's an excerpt:

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'), '🎉');
});

The first test fails. On adding a console.log() to the first test as

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

The first test now passes and the second test fails. On adding a console.log() statement to the second test as well,

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

...both tests pass.

I'm sure I'm doing something silly or missing something out big time. I've been through ava's common pitfalls document and couldn't find anything relevant.

The testcase works correctly. The problem is, that decode is not pure, it returns different results every time you call it, and it only returns the right result at the second call. Therefore if you add a console.log before, the result is right, otherwise it is false:

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

But why does that happen? Well as stated in the 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.

The Regular Expression is stateful and changes its state whenever you call .test() on it, therefore it yields different results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM