Search code examples
node.jsstringjestjsbuffer

Jest fails for same string


I'm trying unit testing for the first time with Jest on a personal project, and some of my tests failed even though the data received was the exact same as expected, here's an example:

test("decrypt method works correctly", () =>{
    const myAES = new rijndael("", "0bdfa595235c307a105d593fb78fbb13", { key: "SOME 128 BIT KEY", bits: 128, rounds: 9 })
    expect(myAES.decrypt()).toStrictEqual({
        "c": "0bdfa595235c307a105d593fb78fbb13",
        "p": "ATTACK AT DAWN!",
        "errors": []
    })
}

Jest report

So then I tried to check if it's a problem with Jest or my code:

const r = myAES.decrypt()
console.log(typeof r.p) // string
console.log(r.p === "ATTACK AT DAWN!") // false

Which just made me even more confused as the strings look the same. The code that I'm testing is an AES encryption function (Don't worry it's just a personal project for fun won't be used in production) that processes text as nodeJS Buffers, and in the end uses the toString() method to convert it back to a string. I'm thinking that may be why I'm having issues, but can't seem to find exactly why. Would love it if someone could point me in the right direction so I can get rid of this error. Thank you in advance.

P.S. I'll save everyone the pain of reading my AES implementation for now as I don't think it's a problem with the encryption but let me know if that's necessary


Solution

  • Ok, so turns out it was a stupid mistake where I overlooked the series of null bytes that tend to end up in the end of the buffer after decryption. While toString() will turn the buffer into the string I want the computer will not recognise it as the same string. So all I had to do was strip the null bytes that follow. Assuming that the null bytes should only appear at the end of the string as they normally do:

    const i = buffer.indexOf(0x00)
    const result = buffer.slice(0, i).toString() //solves the problem