Jest.js 如何正确地预料笑话中错误?

yzckvree  于 2022-12-08  发布在  Jest
关注(0)|答案(4)|浏览(166)

我希望在未定义类属性this.url的情况下进行测试,以预期抛出错误。
我哪里做错了?
第一个
Jest错误消息:

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)
wxclj1h5

wxclj1h51#

另一种方法Assert类中的错误,我发现这是一种更恰当的方法:
第一个

w8biq8rn

w8biq8rn2#

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

    // When
    try {
      const Websocket = new Service()
    } catch(err){
      expect(Websocket.url).toBeUndefined()
      expect(err.message).toBe("Websocket URL is not provided")
      done()
    }
   

   throw new Error('it did not catch url is not provided error')
  })
q0qdq0h2

q0qdq0h23#

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
jchrr9hc

jchrr9hc4#

我想你可能在找更像是

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

想要检查URL是否未定义是可以理解的,但是我不相信在错误之后会执行任何操作,除非您捕获并丢弃它,所以没有设置它不应该是一个显示停止器。

相关问题