如何使用 React 17 在 Storybook 运行的代码中使用 Jest 模拟
我们有一个 React 17 代码库,其中包含大量生成模拟数据类型 save 的函数,因此我们可以在 Jest 运行的不同单元测试中重复使用它们。
export const createMockProject = (
overwrites: Partial<Project> = {}
): Project => ({
id: 'PROJECT_ID',
name: 'PROJECT_NAME',
transfer: jest.fn(), // mock method. Not real code, just to show the schema
...overwrites,
});
对于方法,我们使用 jest.fn()。我们想在 Storybook 中重用这些模拟,并且认为我们可以全局设置 Jest,这样当在 Storybook 中执行调用 jest.fn() 的代码时,实际上永远不会调用 jest。
// inside .storybook/preview.ts
// Initialize global jest.fn override
window.jest = {
fn: ((fnc: any) => fnc) as any,
};
这与使 jest-mock
全局可用的方法类似,如建议的 这里。
问题是,无论哪种方式, React 在协调时检查定义的玩笑,并抛出有关未包含在 act 中的内容的控制台错误,这会妨碍任何开发人员正确关注开发故事书故事时的错误日志。
TextField.tsx:171 Warning: An update to XComponent inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
我看到 Jest 拾取了这个 __DEV__
标志(请参阅链接的 React 代码),但
我很感谢关于如何解决这个问题的建议。
We have a React 17 codebase that has a ton of functions that generate mock data type save, so we can re-use them in different unit tests run by Jest.
export const createMockProject = (
overwrites: Partial<Project> = {}
): Project => ({
id: 'PROJECT_ID',
name: 'PROJECT_NAME',
transfer: jest.fn(), // mock method. Not real code, just to show the schema
...overwrites,
});
For methods, we use jest.fn(). We want to re-use those mocks in Storybook, and figured we could just set Jest globally so that when code executed in storybook that calls jest.fn() actually never calls jest.
// inside .storybook/preview.ts
// Initialize global jest.fn override
window.jest = {
fn: ((fnc: any) => fnc) as any,
};
That is a similar approach to just making jest-mock
globally available, as proposed here.
The problem is that either way, React checks for jest being defined when reconciling, and throws console errors about things not being wrapped in act, which hinders any Developer to properly keep an eye on error logs while developing storybook stories.
TextField.tsx:171 Warning: An update to XComponent inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
I saw this __DEV__
flag (see linked React code) picked up by Jest, but
- to me it is not clear what it is for, it just seems like an example
- setting it to false in the storybook setup file had no effect
- even if it worked, side effects by toggling it are not clear
I appreciate advice in how to tackle this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论