使用useState和setTimeout

时间:2020-07-29 21:22:04

标签: reactjs jestjs react-hooks settimeout enzyme

代码结构与下面给出的相同:

FunctionComponent.js

...
const [open, handler] = useState(false);
setTimeout(() => {handler(true);}, 2000);
...
return (
...
<div className={active ? 'open' : 'close'}>
)

comp.test.js

jest.useFakeTimers();

test('test case 1', () => {
 expect(wrapper.find('open').length).toBe(0);
 jest.advanceTimersByTime(2000);
 expect(wrapper.find('open').length).toBe(1);
 jest.useRealTimers();
});

问题在于测试中用粗体表示的表达式表示开放类的长度仍为0,因此实际值和预期值均不满足​​。

1 个答案:

答案 0 :(得分:0)

您要测试挂钩的结果,而不是挂钩本身,因为这就像测试React一样。您实际上想要进行一个测试,以检查开放类是否存在,然后不存在(反之亦然),就像您正在尝试的那样。

简而言之,要解决您的问题,您需要在选择课程时使用".open"。我还建议对类使用.exists()而不是".length()",然后也可以使用".toBeTruthy()"

您也可以考虑改进以Jest/Enzyme combined格式编写测试的过程:

import { shallow } from 'enzyme';
import { FunctionComponent } from './FunctionComponent.jsx';

jest.useFakeTimers();

describe('<FunctionCompnent />', () => {
  const mockProps = { prop1: mockProp1, prop2: mockProp2, funcProp3: jest.fn() };
  const wrapper = shallow(<FunctionComponent {...mockProps} />);

  afterEach(() => {
   jest.advanceTimersByTime(2000);
  });

  afterAll(() => {
    jest.useRealTimers();
  });

  it('should render as closed initially', () => {
    expect(wrapper.find('.close').exists()).toBeTruthy();
    // you could also add the check for falsy of open if you wanted
    // expect(wrapper.find('.open').exists()).toBeFalsy();
  });

  it('should change to open after 2 seconds (or more)', () => {
    expect(wrapper.find('.open').exists()).toBeTruthy();
    // you could also add the check for falsy of close if you wanted
    // expect(wrapper.find('.close').exists()).toBeFalsy();
  });
});

编辑:对不起,我意识到在再次检查您的代码后我向后编写了测试,现在应该将其修复。