简体   繁体   English

嘲笑测试函数,调用eval

[英]Jest testing function that calls eval

I have a Vue TS project created with vue-cli 3.0. 我有一个使用vue-cli 3.0创建的Vue TS项目。

This is the function I will test: 这是我将测试的功能:

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

And this is my test function using Jest framework: 这是我使用Jest框架的测试功能:

 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. 现在,我收到此消息, 测试失败的控制台日志记录 ,告诉我我需要模拟版本的eval。

How can i mock eval ? 我该如何模拟评估

Update 更新资料

It seems you can't always override eval based on your JS environment (browser or node). 似乎您不能总是基于您的JS环境(浏览器或节点)覆盖eval。 See the answer to "How override eval function in javascript?" 请参阅“如何在javascript中覆盖eval函数?”的答案 for more information 欲获得更多信息

Original answer 原始答案

I think you can redefine eval in your test file: 我认为您可以在测试文件中重新定义eval

global.eval = jest.fn()

You need to track your function with spyOn(). 您需要使用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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM