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?