Search code examples
javascriptclassjestjstddthrow

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


I am new to Javascript and am currently being taught about classes and tests. My test is failing on a test for an error. My class code, test code and test results are below.

Sorry if I am missing something obvious I am very new and have been thrown right into it.

Class:

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


module.exports = Bag

Test Code:

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

Test result:

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.

Solution

  • In your second test, you get and error before the expect statement:

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

    Just remove this line and the test should be fine.