0

I'm trying to use Jest to write unit tests for some JavaScript code I have. The problem is that the code file contains functions that aren't defined or imported, so when I try to import the file to test, Jest throws an error about the undefined functions. Is there a way I can get around this? Only import the functions I want to test, for example?

Here's a snippet of the file with the code that I'm trying to test:

// run any data migrations
on("sheet:opened", () => {
    sheetMigration();

    getAttrs(["btatow_sheet_version"], ({
        btatow_sheet_version
    }) => {
        if (btatow_sheet_version >= 3) {
            recalculateSkills();
        }
    });
});

...

// calculate stat values when XP amount changes
on("change:strength_xp change:body_xp change:reflex_xp change:dexterity_xp change:intelligence_xp change:will_xp change:charisma_xp change:edge_xp", calculateAbilityScore)

const calculateLinkedAttributeValue = attribute => {
    if (attribute > 10) {
        return Math.floor(attribute / 3);
    } else {
        if (attribute < 1)
            return -4;
        else if (attribute < 2)
            return -2;
        else if (attribute < 4)
            return -1;
        else if (attribute < 7)
            return 0;
        else if (attribute < 10)
            return 1;
        else
            return 2;
    }
}

...

// exports for testing
module.exports = calculateLinkedAttributeValue

Here's the code in the test file:

const calculateLinkedAttributeValue = require('./sheet-worker')

test('should calculate linked attribute value for attribute value of 0', () => {
    expect(calculateLinkedAttributeValue(0)).toBe(-4)
})

I have a package.json file set up, and have brought in Jest as a dependency, like so:

{
  "name": "battletech-a-time-of-war",
  "version": "1.0.0",
  "description": "Character sheet for Roll20 for the A Time of War TTRPG system.",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "jest": "^26.0.1"
  },
  "type": "module",
  "sourceType": "module"
}

Attempting to run the tests via the command line produces the following output:

C:\Stuff\Development\roll20-character-sheets\BattleTech-A-Time-of-War\development>npm run test

> battletech-a-time-of-war@1.0.0 test C:\Stuff\Development\roll20-character-sheets\BattleTech-A-Time-of-War
> jest

 FAIL  development/sheet-worker.test.js
  ● Test suite failed to run

    ReferenceError: on is not defined

      1 | // run any data migrations
    > 2 | on("sheet:opened", () => {
        | ^
      3 |     sheetMigration();
      4 |
      5 |     getAttrs(["btatow_sheet_version"], ({

      at Object.<anonymous> (development/sheet-worker.js:2:1)
      at Object.<anonymous> (development/sheet-worker.test.js:1:39)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.226 s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! battletech-a-time-of-war@1.0.0 test: `jest`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the battletech-a-time-of-war@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\<User>\AppData\Roaming\npm-cache\_logs\2020-06-01T09_59_15_484Z-debug.log

EDIT: Add examples and remove link to GitHub source code.

  • Define all of them as globals and clean them up after a test. Please, update the question with the code, it should be understandable without navigating to external resource which can become unavailable. It's not unnecessary to paste a thousand of lines, just https://stackoverflow.com/help/mcve – Estus Flask May 31 '20 at 08:14
  • The question needs more focus. You have too much code – Lin Du Jun 01 '20 at 04:10
  • What should I remove from the question? I've tried to include the minimal information; the code that I'm trying to test, along with the code that's causing the problem, the test code, and the error output. I included the `package.json` as I thought that may be relevant to the question, in case I have Jest set up incorrectly. – Michael Smith Jun 04 '20 at 09:57

1 Answers1

0

After digging around for a while on the internet and trying different things, I was able to determine the cause of the problem. It's actually nothing to do with Jest, it's the Node require() function. I found out from this StackOverflow comment that the Node require() function basically runs all the code in the file you're importing. Hence it tries to run the undefined functions, and errors.