buffer
buffer copied to clipboard
Functions that use Buffer will have TypeError in jest unit testing
My function contains the following code :
// data here is a Buffer obj example: data = Buffer('xxxx', 'base64')
var isBuffer = typeof data.readUInt32BE === 'function' && typeof data.slice === 'function';
if (isBuffer) {
this.highStart = data.readUInt32BE(0);
this.errorValue = data.readUInt32BE(4);
uncompressedLength = data.readUInt32BE(8);
data = data.slice(12);
} else {
var view = new DataView(data.buffer);
this.highStart = view.getUint32(0);
this.errorValue = view.getUint32(4);
uncompressedLength = view.getUint32(8);
data = data.subarray(12);
} // double inflate the actual trie data
I use "buffer": "^6.0.3"
I wrote a jest unit test for my function. It can pass when I run in the node environment, but if I set testEnvironment to jsdom, an error will appear as shown in the figure below.

Debug found that it seems that fromObject in buffer-es6 cannot handle this ArrayBuffer object. Is there any good way to circumvent this problem?

I don’t know if this is a jsdom problem or a Buffer problem?
I'd like to bump this thread as I'm seeing the same issue using Cypress.
const response = await this.nativeFetch.apply(context, [
pollyRequest.url,
{
...options,
method: pollyRequest.method,
headers: pollyRequest.headers,
body: pollyRequest.body
}
]);
const buffer = Buffer.from(await response.arrayBuffer());
response.arrayBuffer() returns an ArrayBuffer which is failing buffer-es6's instanceof check.