【问题标题】:is my syntax wrong with throwing new error? My test is failing... not sure why抛出新错误是我的语法错误吗?我的测试失败了......不知道为什么
【发布时间】:2021-01-22 07:13:48
【问题描述】:

我是 Javascript 新手,目前正在学习课程和测试。我的测试在测试错误时失败。我的类代码、测试代码和测试结果如下。

如果我遗漏了一些明显的东西,我很抱歉,我很新并且已经被扔进去了。

类:

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.

【问题讨论】:

    标签: javascript class jestjs tdd throw


    【解决方案1】:

    在您的第二次测试中,您在期望语句之前得到和错误:

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

    只要去掉这一行,测试就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多