Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jest: toBeInstanceOf(Object) fails

Just checking that we're exporting an object is failing as follows:

import * as Foo from './foo';

describe('Foo', () => {
  test('should export an object', () => {
    expect(Foo).toBeInstanceOf(Object);
  });
});

getting this error:

expect(received).toBeInstanceOf(expected)

While I can workaround using typeof:

import * as Foo from './foo';

describe('Foo', () => {
  test('should export an object', () => {
-    expect(Foo).toBeInstanceOf(Object);
+    expect(typeof LivingAppsCoreReact).toEqual('object');
  });
});

I'd like to understand why Jest defines that Object constructor isn't... Object constructor.

Checked that the object is exporting the actual keys ✅


Env:

$» npm ls jest                                                            1 ↵
[email protected]
├── [email protected]
└─┬ [email protected]
  └── [email protected] deduped
like image 944
Manu Avatar asked Sep 16 '25 08:09

Manu


1 Answers

This might be a bug on Jest/Node side, as the globals on Jest environment differ from Node's, see:

  • https://github.com/facebook/jest/issues/2549
  • https://github.com/nodejs/node/issues/31852
  • https://github.com/nodejs/node/issues/46558

When you use a default export, the type of your exported element is Object, and then when you compare it to "Jest's Object type" that fails the test as they're in different contexts.

This is also related to behaviors like: https://stackoverflow.com/a/75524385/5078746


In your case, you can use destructuring in case you are using named exports (e.g export const Foo = {...}) which will lead Jest to evaluate your objects in the same context.

I mean move from

import * as Foo from './foo';

To

import { Foo } from './foo';

Or, you can check for object properties with .toMatchObject(object) instead of checking if the Object is an Object.

like image 169
Fcmam5 Avatar answered Sep 17 '25 22:09

Fcmam5