Last Updated: February 25, 2016
·
2.554K
· abe33

Spying on require with jasmine

I recently encountered a situation where I needed to test how a program behave when a call to require throw an exception (module not found). After some googling I found the following solution:

describe 'spying on require', ->
  beforeEach ->
    spyOn(require('module'), '_load').andCallFake ->
      throw new Error 'irrelevant'

  it 'should allow to make any require call to fail', ->
    expect(-> require 'fs').toThrow()