Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load your classes in Jest?

So this question seems really stupid, but I've been searching and searching, and have not found an answer.

I'm trying out the Jest framework for unit testing my custom javascript project, which is not using React or any other framework. My project structure currently looks like this:

  • project
    • js
      • main.js <-- all my classes are in here, es6 style, if that matters
    • --tests--
      • card.test.js <-- tests are in here

Inside main.js there is class Card defined. I doubt there are any issues with the file, as I've run it perfectly fine in the browser.

"use strict";

class Card 
{
  ...
}

The one test I've written so far, just to see if it works is:

require('../js/main.js');

test("stuff", () => {
    let card = new Card(1, 1);
});

When I try to run the test:

yarn test

But all I'm getting is:

    ReferenceError: Card is not defined

      2 |
      3 | test("stuff", () => {
    > 4 |       let card = new Card(1, 1);
        |                  ^
      5 | });

      at Object.<anonymous>.test (__tests__/card.test.js:4:13)

It seems like main.js is getting loaded, because if I add a console.log() in it, that gets output when I run the test. So why is it complaining that Card is not defined?

like image 385
Kai Avatar asked Dec 29 '25 09:12

Kai


1 Answers

I got something that seems to work, though using ES6 modules.

  1. I changed all the classes in main.js to be modules (as well as separating them out into views.js, controllers.js, and models.js):
"use strict";

export class Card 
{
  ...
}
  1. I installed some babel node modules through yarn:
yarn add --dev @babel/core @babel/cli @babel/preset-env
  1. I added a .babelrc file in my project root:
{
    "presets": ["@babel/preset-env"]
}
  1. I changed my test to match what Andre suggested
const { Card } = require('../js/models.js');

test("stuff", () => {
    let card = new Card(1, 1);
});

Now there are no errors when running

yarn test

like image 134
Kai Avatar answered Jan 01 '26 01:01

Kai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!