1

I have a Vue TS project created with vue-cli 3.0.

This is the function I will test:

public hopJavascript(url: string) {
    eval(url);
}

And this is my test function using Jest framework:

test('navigation using javascript', () => {
    const url = "someurl";
    hopJavascript(url);
    
    expect(eval).toBeCalled();
});

Now i get this message,test failed console logging which is telling me that I need a mocked version of eval.

How can i mock eval ?

2 Answers 2

1

Update

It seems you can't always override eval based on your JS environment (browser or node). See the answer to "How override eval function in javascript?" for more information

Original answer

I think you can redefine eval in your test file:

global.eval = jest.fn()
Sign up to request clarification or add additional context in comments.

3 Comments

Then it says [ts] Cannot find name 'global'. [2304], do you know how to get ts recognize this
After some research, it looks like you cannot always override eval
Nice, but it is old, maybe something changed.
0

You need to track your function with spyOn().

This solution should work for you.

import MyClass from '../MyClass';

test('navigation using javascript', () => {
    const url = "someurl";
    const spy = jest.spyOn(MyClass, 'eval');

    MyClass.hopJavascript(url);

    expect(spy).toHaveBeenCalled();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.