首页 > 解决方案 > Javascript 中的玩笑测试 - 它测试不应该测试的一行

问题描述

我是 Jest 测试的新手,我为我的程序中的一个函数创建了一个测试。它用于测试函数,根据所有 3 个边的长度选择三角形的类型(例如,如果所有 3 个边相等,则返回“等边”。

当我运行我的程序时,一切都很好,但是当我通过命令“yarn test”运行测试时,它说测试失败,因为“ReferenceError: document is not defined in line 2”。但是在我的测试功能中,没有提到文档的行。

这是我的功能 -

const triangleType = (side1, side2, side3) => {
    //check, if exists
    if (
      side1 + side2 <= side3 ||
      side1 + side3 <= side2 ||
      side2 + side3 <= side1
    ) {
      return "Non existing";
    }

    if (side1 === side2 && side2 === side3) {
      return "Equilateral";
    }

    if (side1 === side2 || side1 === side3 || side2 === side3) {
      return "Isosceles";
    }

    return "Scalene";
  };

module.exports = triangleType;

这是我的 Jest 测试用例 -

const triangleType = require('./file');


test('Similar sides to be "Equilateral"', () => {
    expect(triangleType(1,1,1)).toBe("Equilateral")
  })

还有我的控制台,测试用例发生的地方 -

S C:\Users\aannu\Desktop\front end task> yarn test
yarn run v1.22.10
warning package.json: No license field
$ jest
 FAIL  ./file.test.js
  ● Test suite failed to run

    The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.
    Consider using the "jsdom" test environment.

    ReferenceError: document is not defined

      1 | //defining canvas
    > 2 | const container = document.getElementById("container");
        |                   ^
      3 | const canvas = document.getElementById("canvas");
      4 | const ctx = canvas.getContext("2d");
      5 | let cw = canvas.width,

      at Object.<anonymous> (file.js:2:19)
      at Object.<anonymous> (file.test.js:2:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.869 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

标签: javascripttestingjestjs

解决方案


推荐阅读