gpt4 book ai didi

react-dnd - 多个 React-dnd 开玩笑测试 "Cannot have two HTML5 backends at the same time"

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

我有一个 Jest 测试文件,其中包含许多测试。

import React from 'react';
import configureStore from 'redux-mock-store';
import {Provider} from "react-redux";
import renderer from "react-test-renderer";
import HTML5Backend from "react-dnd-html5-backend";
import {DragDropContextProvider} from "react-dnd";

describe('My Component Tests', () => {
let mockStore;
let store;

beforeEach(() => {
mockStore = configureStore();
store = mockStore(mockData);
});

test(' test1', () => {
const cmpt = <Provider store={store}>
<DragDropContextProvider backend={HTML5Backend}>
<MyComponent state={1}/>
</DragDropContextProvider>
</Provider>;

const tree = renderer.create(cmpt).toJSON();
expect(tree).toMatchSnapshot();
});

test(' test2', () => {
const cmpt = <Provider store={store}>
<DragDropContextProvider backend={HTML5Backend}>
<MyComponent state={2}/>
</DragDropContextProvider>
</Provider>;

const tree = renderer.create(cmpt).toJSON();
expect(tree).toMatchSnapshot();
});
});

第一次测试总是有效

但是后续的总是出现这个错误:
 Error: Uncaught [Error: Cannot have two HTML5 backends at the same time.]

我猜这是因为 HTMLBackend 被视为单例,并且在测试中使用,这不是我想要的。我想要独立运行的测试。

是否有一些是在 中创建 HTMLBackend 的实例? beforeEach() 功能。

我试图将 HTML5Backend 封装成一个单例,但我遇到了同样的问题:
let html5Backend = null;

function getSingleton() {
if (!html5Backend) {
html5Backend = HTML5Backend;
debugger;
}
return html5Backend;
}

最佳答案

我通过在“描述”级别引用 HTMLBackend 实例解决了这个问题,如下所示:

describe('My Component Tests', () => {
let mockStore;
let store;

let htmlbe = HTML5Backend; //reference instance here!!!

beforeEach(() => {
mockStore = configureStore();
store = mockStore(mockData);
});

test(' test1', () => {
const cmpt = <Provider store={store}>
<DragDropContextProvider backend={htmlbe }>
<MyComponent state={1}/>
</DragDropContextProvider>
</Provider>;

const tree = renderer.create(cmpt).toJSON();
expect(tree).toMatchSnapshot();
});

test(' test2', () => {
const cmpt = <Provider store={store}>
<DragDropContextProvider backend={htmlbe }>
<MyComponent state={2}/>
</DragDropContextProvider>
</Provider>;

const tree = renderer.create(cmpt).toJSON();

这相当于在所有测试中都有一个单例。

关于react-dnd - 多个 React-dnd 开玩笑测试 "Cannot have two HTML5 backends at the same time",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58077693/

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