Search code examples
javascripttypescriptjestjsjavascript-objects

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

Solution

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

    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.