反应:酶的局部范围不起作用



我正在使用React。我使用redux工具箱使用了基本的redux计数器。我对测试真的很陌生。我正在使用Enzyme和Jest进行测试。我的redux计数器初始状态为1。根据我的测试,在it范围内,我首先获取初始状态,然后在模拟("点击"(增加按钮后,我得到了我预期的结果2。当我尝试在it范围内测试我的减少按钮时,它会从增加的it范围中获取结果。如果我把initialState 1放在减少按钮的it范围内,它会给我一个失败的测试,因为它需要2。

这是我的测试文件

import React from 'react';
import { mount } from "enzyme"; // mount is fulldom renderning function with children
import Counter from 'components/counter';
import Root from "root/index"; // this is the root index which connect react component and redux
let wrapped;
beforeEach(() => {
wrapped = mount(
<Root>
<Counter />
</Root>
);
});
afterEach(() => {
wrapped.unmount(); // it cleans the mount after test.
});
describe(`This is counter component`, () => {
it(`This is show intial Value`, () => {
expect(wrapped.find(`h1`).text()).toEqual(`1`);
});
it(`after click it will increase the value`, () => {
expect(wrapped.find(`h1`).text()).toEqual(`1`);
wrapped.find(`button`).at(0).find(`[data-test="increment"]`).simulate(`click`);
expect(wrapped.find(`h1`).text()).toEqual(`2`);
});
it(`after click it will decrease the value`, () => {
expect(wrapped.find(`h1`).text()).toEqual(`1`); // test failed because it expect 2
wrapped.find(`button`).at(1).find(`[data-test="decrement"]`).simulate(`click`);
expect(wrapped.find(`h1`).text()).toEqual(`0`);
});
});

这是我的计数器组件

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from 'store/reducer/counter/index';
import { IRootState } from 'store/combineReducer';
import styled from 'styled-components';
const Button = styled.button`
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
`;
const Text = styled.h1`
color: blue;
`;
export default () => {
const counter = useSelector((state: IRootState) => state.counter);
const dispatch = useDispatch();
return (
<div >
<Text>{counter}</Text>
<Button data-test="increment" onClick={() => dispatch(increment())}>
Increment counter
</Button>
<br></br>
<br></br>
<Button data-test="decrement" onClick={() => dispatch(decrement())}>
Decrement counter
</Button>
</div>
);
};

it块有一个作用域,从某种意义上说,函数有一个范围,此外,间谍等其他事情可能会受到当前运行的测试的影响。这里的作用域没有问题,唯一受作用域影响的是wrapper变量,它是在所有测试通用的作用域中定义的。由于它在beforeEach中被重新分配,因此不会导致测试交叉污染。

这里的问题是存在全局状态,因为Redux自然提供全局状态。

最常见的情况是为测试设置自定义存储,因此初始值等可以根据测试需求进行操作:

let wrapped;
beforeEach(() => {
const store = ...
wrapped = mount(
<Provider store={store}><Counter /></Provider>
);
});

这是文档中的建议。

或者,每次测试都需要重新导入一个存储和所有直接依赖它的模块,而不是这些模块的顶级导入:

let wrapped;
let Root;
beforeEach(() => {
jest.resetModules();
Root = require("root/index");
wrapped = mount(
<Root>
<Counter />
</Root>
);
});

最新更新