The assertion of `expect.toBeInstanceOf(Object)` fails in Jest

Just wanted to verify if we're exporting an object, but the test is failing as shown below:

import * as Foo from './foo';

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

encountering this error message:

https://i.sstatic.net/j9FoR.png

However, I found a 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 am curious to know why Jest doesn't recognize the Object constructor as... the Object constructor.

Confirmed that the object is indeed exporting the correct keys ✅


Environment details:

$» npm ls jest                                                            1 ↵
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04697d2974766b6e61677044342a37352a31">[email protected]</a>
├── <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771d12040337454e59445946">[email protected]</a>
└─┬ <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9aeee9b7f0ffe9eedaa8a3b4aab4a9">[email protected]</a>
  └── <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="28424d5b5c681a11061b0619">[email protected]</a> deduped

Answer №1

It appears there may be a potential issue with Jest and Node regarding global variables, as the environments of Jest and Node differ from one another. For more information, please refer to the following links:

If you are using a default export, your exported element will be of type Object. When comparing this to "Jest's Object type," it may cause the test to fail due to the different contexts.

This situation is also connected to scenarios like:


To resolve this issue in your code, consider using object destructuring if you are utilizing named exports (e.g export const Foo = {...}). This will allow Jest to evaluate your objects within the same context.

In other words, transition from

import * as Foo from './foo';

To

import { Foo } from './foo';

Alternatively, you can verify object properties using .toMatchObject(object) instead of checking if the Object is an Object.

Answer №2

The Debate Between Jest Globals and Node Globals

One of the ongoing discussions revolves around the differences between Jest and Node globals. It's essential to understand that there are distinctions between the Jest global variables and the Node global variables. For more detailed information, you can refer to this open issue on Github: Jest globals differ from Node globals.

Simply put, the behavior of the toBeInstanceOf function varies depending on whether it is operating on instances of classes that you have created or instances of the global Array class. When asserting against the example provided above, using the toBeInstanceOf function is recommended. Take a look at the documentation for toBeInstanceOf and the code snippet below for clarification.

This information is sourced from the documentation itself.

describe('toMatchObject applied to arrays', () => {
  test('the number of elements must match exactly', () => {
    expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]);
  });

  test('.toMatchObject is called for each element, allowing for extra object properties', () => {
    expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([
      {foo: 'bar'},
      {baz: 1},
    ]);
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I convert a Java array of arrays into JavaScript?

When working with Java, I need to create a JSON structure similar to this: [ [ timestamp , number ],[ timestamp , number ] ] This structure is necessary for displaying data on Highcharts graphs. I initially used a "LinkedList of LinkedList" format to ...

What is the best way to conceal a specific class of DIV within a container, and how can I also hide another DIV within the same container by

I have a DIV class containing around 10 elements within a container. I am looking to implement a feature where these elements are hidden and shown one by one every 15 seconds using jQuery with a smooth fadeOut() effect. Your assistance in achieving this wo ...

Artwork - Circular design disappears without warning

While working on a clock project purely for enjoyment, I noticed that the minute arc disappears from the canvas as soon as a new minute begins. Any idea why this is happening? Check out the clock in action: https://jsfiddle.net/y0bson6f/ HTML <canvas ...

Conceal Div based on user input

There is one input text box for the user and an array with different elements within. When the user types "ha," all elements that do not contain "ha" should be hidden. Whenever the input is triggered, a function is called to hide and display specific ele ...

"Implement a shuffle function in JavaScript to randomize an array when a submit

My goal is to when a user clicks submit on an input in JavaScript, I want to shuffle an array and display the first element in a div with the ID 'message'. Upon subsequent submits, I would like to display the next elements of the array following ...

reconfigure keyboard shortcuts in web browser

In the popular web browser Google Chrome, users can quickly jump to the next tab by pressing CTRL + TAB. Is there a way to change or disable this shortcut? The provided code snippet does not seem to work as intended. $(document).keydown(function(e){ ...

Transform date format using VueJS in JavaScript

I need to convert a date format from 19 Oct 2017 to 20171019. Is there a way to do this quickly? I am using FlatPickr in VueJs. Here is the code snippet for reference: import flatPickr from 'vue-flatpickr-component'; import 'flatpickr/dist/ ...

modifying a JSON document

After exploring various options, questions, and answers, I have come to the conclusion that none of them were suitable for my current project. My project involves a shopping cart system created using PHP sessions, which is functioning well. Users can add ...

How can you update ngModel in Angular and mark the form as dirty or invalid programmatically?

My form is connected to a model as shown below In the component file: myTextModel: string; updateMyTextModel(): void { this.myTextModel = "updated model value"; //todo- set form dirty (or invalid or touched) here } Html template: <form #test ...

Optimizing Performance in THREE .JS Raycasting

I am attempting to determine the shortest distance from a point to a large, intricate Mesh along a plane within a specific direction range: for (var zDown in verticalDistances) { var myIntersect = {}; for (var theta = Math.PI / 2 - 0.5; theta &l ...

having difficulty interpreting the information from angular's httpclient json request

After creating an Angular function in typescript to make an http request for JSON data and save it to an object, I noticed that the function requires two clicks of the associated button to work properly. Although the connection and data parsing are success ...

What can be found inside event.target and the ways to retrieve its values

Currently, I am participating in an online workshop that includes examples which you can access at this link: https://openlayers.org/en/latest/examples/mouse-position.html. In the example provided in the link above, two functions are utilized. var projecti ...

Angular form retains the previous value when saving

I encountered an issue with my form component where it displays previous values instead of updated ones during a save operation. The strange part is that if I close the form and reopen it, the new values are then shown correctly. It seems like the problem ...

The elusive cookie in NodeJS remained just out of reach

After setting a cookie using the code below: router.get("/addCartToCookie", function(req, res) { let options = { maxAge: 1000 * 60 * 15, httpOnly: true, }; let cartData = { name: "test cookie", slug: slugify(&quo ...

When navigating between Dynamic Pages using NuxtLink, the store data is not accessible

Check out the demo below. Click here for stackblitz When transitioning from a top page to a post page, the correct content is displayed. However, moving from one post page to another does not display the correct content immediately. Reloading the page w ...

Tips for closing a Modal Dialog in Vue3 using a different component, such as PimeVue

I'm currently working on implementing a Dialog component and integrating it into another component. I have managed to open the Dialog when a button is clicked, but I am facing difficulty in figuring out how to close it. Below are the details of the co ...

Error during Next.js build: Incompatible types - cannot assign type to 'never'

Encountering an error in the console while attempting to build my project: .next/types/app/facebook/page.ts:8:13 Type error: Type 'OmitWithTag<typeof import("D:/projects/abkh24/client/app/facebook/page"), "metadata" | "defa ...

Testing an rxjs observable using Jest: a beginner's guide

Consider the following code snippet which defines a function that returns an observable : retrieveAll = (): Observable<Well[]> => from(this.wellRepository.retrieveAssets()).pipe( map((assets: Asset[]) => this.mapper.mapping(assets)), ...

Is it feasible to implement early-return typeguards in Typescript?

There are instances where I find myself needing to perform type checks on variables within a function before proceeding further. Personally, I try to minimize nesting in my code and often utilize early-return statements to keep the main functionality of a ...

Issue in Next.js 13: Byte index exceeds limits when running 'npm run dev' command

When attempting to install Next.js 13.4.12, I utilized the command npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385b4a5d594c5d15565d404c1559484878090b160c1609">[email protected]</a>. The installation process ...