Home > OS >  how to expect an error in jest correctly?
how to expect an error in jest correctly?

Time:11-16

I would like a test to expect a Thrown Error in case a class property this.url is not defined.

What am I doing wrong here ?

  it('should throw an error if url is not provided by default', async () => {
    // Given
    const Service = require('./services/websocket')

    // When
    const Websocket = new Service()

    // Then
    expect(Websocket.url).toBeUndefined()
    expect(Websocket).toThrowError('Websocket URL is not provided')
  })
// services/websocket.js

class Websocket {
  constructor () {
    this.url = undefined

    if (!this.url) {
      throw new TypeError('Websocket URL is not provided')
    }
  }
}

module.exports = Websocket

Jest error message:

 FAIL  terminal.test.js
  Websocket service provider
    ✕ should throw an error if url is not provided by default (2 ms)

  ● Websocket service provider › should throw an error if url is not provided by default

    TypeError: Websocket URL is not provided

      4 |
      5 |     if (!this.url) {
    > 6 |       throw new TypeError('Websocket URL is not provided')
        |             ^
      7 |     }
      8 |   }
      9 | }

      at new Websocket (services/websocket.js:6:13)
      at Object.<anonymous> (terminal.test.js:7:23)

CodePudding user response:

I've managed to make it work.


  it('should throw an error if url is not provided by default', () => {
    // Given
    const Service = require('./services/websocket')

    // When
    let Module

    try {
      Module = new Service()
    } catch (error) {
      Module = error
    }

    expect(Module).toBeInstanceOf(Error)
    expect(Module.message).toBe('Websocket URL is not defined')
  })

  it('should pick up a WS url from env file automatically', () => {
    process.env.WS_URL = 'ws://dummyurl'
    const Service = require('./services/websocket')
    const Module = new Service()

    expect(Module.url).toEqual(process.env.WS_URL)
  })
// services/websocket.js

class Websocket {
  constructor () {
    this.url = process.env.WS_URL

    if (!this.url) {
      throw new Error('Websocket URL is not defined')
    }
  }
}

module.exports = Websocket

CodePudding user response:

I think you're probably looking for something more like

it('should throw an error if url is not provided by default', () => {
  const Service = require('./services/websocket')
  expect(new Service()).toThrowError()
})

The want to check for the URL to be undefined is understandable, but I don't believe anything would execute after the error unless you catch and discard it, so the lack of it being set shouldn't be a show stopper.

  • Related