【问题标题】:Using Jest to test code that contains undefined functions使用 Jest 测试包含未定义函数的代码
【发布时间】:2020-09-18 15:08:02
【问题描述】:

我正在尝试使用 Jest 为我拥有的一些 JavaScript 代码编写单元测试。问题是代码文件包含未定义或未导入的函数,因此当我尝试导入文件进行测试时,Jest 会抛出有关未定义函数的错误。有没有办法解决这个问题?比如只导入我想测试的函数?

这是文件的 sn-p,其中包含我要测试的代码:

// 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

这是测试文件中的代码:

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

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

我设置了一个 package.json 文件,并引入了 Jest 作为依赖项,如下所示:

{
  "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"
}

尝试通过命令行运行测试会产生以下输出:

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

编辑:添加示例并删除指向 GitHub 源代码的链接。

【问题讨论】:

  • 将它们全部定义为全局变量并在测试后清理它们。请用代码更新问题,它应该是可以理解的,而无需导航到可能变得不可用的外部资源。不用贴一千行,stackoverflow.com/help/mcve
  • 这个问题需要更多的关注。你的代码太多
  • 我应该从问题中删除什么?我试图包含最少的信息;我正在尝试测试的代码,以及导致问题的代码、测试代码和错误输出。我包括了package.json,因为我认为这可能与问题有关,以防我的 Jest 设置不正确。

标签: javascript jestjs


【解决方案1】:

在互联网上搜索了一段时间并尝试了不同的方法后,我能够确定问题的原因。其实跟Jest没什么关系,是Noderequire()函数。我从this StackOverflow comment 发现,Node require() 函数基本上运行了您正在导入的文件中的所有代码。因此它会尝试运行未定义的函数和错误。

【讨论】:

    猜你喜欢
    • 2013-03-18
    • 2023-03-14
    • 2021-04-24
    • 2020-07-13
    • 1970-01-01
    • 2019-07-22
    • 2019-09-11
    • 2022-06-30
    • 1970-01-01
    相关资源
    最近更新 更多