buffer icon indicating copy to clipboard operation
buffer copied to clipboard

Functions that use Buffer will have TypeError in jest unit testing

Open abbydad opened this issue 4 years ago • 1 comments

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.

image

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

image

I don’t know if this is a jsdom problem or a Buffer problem?

abbydad avatar Mar 11 '21 03:03 abbydad

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.

offirgolan avatar May 26 '21 18:05 offirgolan