gpt4 book ai didi

reactjs - 使用随机生成的 id (uuid) 进行 Jest 快照测试 React 组件

转载 作者:行者123 更新时间:2023-12-03 13:35:28 25 4
gpt4 key购买 nike

我正在尝试为使用 uuid 生成唯一 id 的 React 组件创建 Jest 快照测试。我正在尝试模拟 uuid 功能。但 mock 似乎不起作用。

组件:

import React from 'react';
import v1 from 'uuid/v1';

class MyComponent extends React.Component {
// Other codes ...

render() {
const id = v1();
return (
<div>
<label htmlFor={id}>
<input type="checkbox"/>
</label>
</div>
)
}
}

export default MyComponent;

测试:

import React from 'react';
import renderer from 'react-test-renderer';
import MyComponent from './MyComponent';

describe('<MyComponent/>', () => {
it('renders correctly', () => {
jest.mock('uuid/v1', () => jest.fn(() => 1));
const tree = renderer.create(<Checkbox />).toJSON();
expect(tree).toMatchSnapshot();
});
});

最佳答案

问题是您在导入要测试的模块后模拟了该模块。因此导入的模块导入了原始版本的uuid/v1。然后您模拟 uuid/v1 但这对 MyComponent 没有影响,因为它已经引用了原始版本。

当在测试的最外层 block 中使用 jest.mock 时,它将被提升到模块的顶部,因此 jest 会在之前模拟 uuid/v1它可以导入到 MyComponent 这就是它在这种情况下起作用的原因

关于reactjs - 使用随机生成的 id (uuid) 进行 Jest 快照测试 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49546495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com