抛出新错误是我的语法错误吗?我的测试失败了......不知道为什么

is my syntax wrong with throwing new error? My test is failing... not sure why

我是 Javascript 的新手,目前正在学习 classes 和测试。我的测试因错误而失败。我的class代码、测试代码和测试结果如下。

抱歉,如果我遗漏了一些明显的东西,我是新手,刚被扔进去。

Class:

class Bag {
    constructor(weight) {
        if (!weight) throw new Error("bag must have a weight")
        this.weight = weight
    }
}


module.exports = Bag

测试代码:

const { TestScheduler } = require("jest")

const Bag = require("./bag")

describe("bag", () => {
    test("has a weight", () => {
        const bag = new Bag(13)
        expect(bag.weight).toBe(13)
    })
    test("bag must have a weight", () => {
        const bag = new Bag()
        expect(() => new Bag()).toThrowError("bag must have a weight")
    })
})

测试结果:

Debugger attached.
 FAIL  ./airport.test.js
  bag
    ✓ has a weight (1 ms)
    ✕ bag must have a weight (1 ms)

  ● bag › bag must have a weight

    bag must have a weight

      2 |     constructor(weight) {
      3 |         if (!weight) {
    > 4 |             throw new Error("bag must have a weight")
        |                   ^
      5 |         }
      6 |         this.weight = weight
      7 |     }

      at new Bag (bag.js:4:19)
      at Object.<anonymous> (airport.test.js:11:21)

  console.log
    16

      at Object.<anonymous> (bag.js:11:9)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.166 s
Ran all test suites.
Waiting for the debugger to disconnect...
npm ERR! Test failed.  See above for more details.

在您的第二次测试中,您在 expect 语句之前遇到错误:

test("bag must have a weight", () => {
        const bag = new Bag() // here!
        expect(() => new Bag()).toThrowError("bag must have a weight")
    })

只需删除此行,测试应该没问题。