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)
new Service()is. This error itself is not handled by your test. Nevertheless it's a little bit strange that your class is namedServiceand notWebsocketas seen in the class definition.expect(Websocket).toThrowError('Websocket URL is not provided')- you expect accessing the variable to throw an error? Even if you did, that access would be done beforeexpectgot called, in an attempt to resolve the value to pass to it, so couldn't be caught. Look again at the examples in the docs, and think about how JS control flow works: jestjs.io/docs/expect#tothrowerror.