0

I'm trying to test a try catch block using Jest. E.g.

// filename: foo.js

const foo = () => {
  let js = 'somejs'
  try {
    eval(js)  
  } catch (e) {
    document.location = 'redirect/to/page'
    return false
  }
  return true
}

export default foo

Do you mock eval (not my choice to use eval. It's my bosses code) and then get it to throw? If so, how would you do that? E.g.

eval = jest.fn()    // doesn't work 

So the test code might be:

// filename: foo.spec.js

import foo from './foo'
eval = jest.fn()

describe('foo', () => {
  describe('when eval succeeds', () => {
    it('performs an eval', {
    const result = foo()
    expect(result).toEqual(true)
  })
  describe('when eval fails', () => {
    beforeEach(() => {
      eval.mockImplementation(() => {throw 'error'})
    })
    it('catches the error and redirects', () => {
      const result = foo()
      expect(result).toEqual(false)
    })
  })
})

What would the mocking and test code look like?

Ben
  • 5,085
  • 9
  • 39
  • 58
  • 4
    First [`eval()` is evil](https://stackoverflow.com/q/86513/1078886) and most problems can be solved without. `eval()` appears to be a non-unforgeable function, thus is can be overwritten _on the `window` object_ (just assigning to eval does not help, you've to replace the global object's property; crude example: `window.eval = ...`). This can be done with mocking facility of your choice. Here's an answer elaborating a bit on mocking [`location` attributes](https://stackoverflow.com/a/36678937/1078886), though it uses Sinon for mocking the principal is the same for other mocking tools. – try-catch-finally Jul 20 '17 at 05:32
  • No arguments re `eval`. It's my bosses code. I can't alter it. But I don't know how to mock out `window` using Jest when it is not wrapped in a helper function (again, it's my bosses code, not mine). From your answer at the other SO question, It sounds like you simply can't mock `window` directly, unless it is wrapped in a helper function. If you can mock it, how do you do that in Jest? [Here is a link to an unanswered question that deals directly with this issue](https://stackoverflow.com/questions/45200395/jest-mock-window-or-document-object): – Ben Jul 20 '17 at 13:50

0 Answers0