Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我们可以模拟节点模块组件中的函数吗?_Javascript_Reactjs_Jestjs_Enzyme_Snapshot - Fatal编程技术网

Javascript 我们可以模拟节点模块组件中的函数吗?

Javascript 我们可以模拟节点模块组件中的函数吗?,javascript,reactjs,jestjs,enzyme,snapshot,Javascript,Reactjs,Jestjs,Enzyme,Snapshot,我有一个复选框组件作为我的应用程序的节点模块 复选框组件: import React from 'react'; import uuidv4 from 'uuid/dist/v4'; export default ({inputProps}) => { let id = uuidv4(); return ( <input type="checkbox" {..

我有一个复选框组件作为我的应用程序的节点模块

复选框组件:

import React from 'react';
import uuidv4 from 'uuid/dist/v4';

export default ({inputProps}) => {
    let id = uuidv4();
    return (
            <input
                type="checkbox"
                {...inputProps}
                id={id}
            />
    );
};
这模拟了我的应用程序中的任何用法,但不模拟复选框组件或任何其他节点模块中的功能。 如果缺少任何导入,请忽略


我能够成功运行测试,但我想找到一种方法来忽略快照文件中UUID的生成。

您可能不应该从
包/dist/
导入,请尝试

import { v4: uuidv4 } from 'uuid';
要模拟,请尝试使用以下方法:

jest.mock("uuid", () => {
  return {
    v4: () => 'test id'
  }
});

另请参见游乐场(它工作):

不工作,仍在生成新id。显然,默认用法已更改。查看更新的答案-现在应该可以了。正如我在描述中提到的,如果在App.js文件中设置了uuid,就像在你的游乐场中一样,我们可以模拟它。但是我可以模拟节点模块中的函数吗?在我的例子中,我尝试测试App.js,它包含从节点模块导入的复选框组件,其中包含uuid生成。我可以模拟复选框组件中生成的uuid吗?为什么需要它?只嘲笑一次?然后您应该使用jest.mockImplementation,然后根据您的用例使用.mockClear、.mockReset或.mockRestore。请看,由于uuid是在我的应用程序之外生成的,即使我在我的应用程序中模拟了
uuid
,它仍然会在快照文件中生成随机id。
jest.mock('uuid/dist/v4', () => {
    return () => 'test id';
});
import { v4: uuidv4 } from 'uuid';
jest.mock("uuid", () => {
  return {
    v4: () => 'test id'
  }
});