2

假设我有以下基本组件Basic.js

import React, { useState, useEffect } from 'react';

export default () => {
  const [items, setItems] = useState([{ name: 'original' }]);

  useEffect(() => {
    setItems([{ name: 'new1' }, { name: 'new2' }]);
  }, []);

  return (
    <div>{items && items.map((item, i) => <div key={i}>{item.name}</div>)}</div>
  );
};

使用react-test-renderer,我可以编写以下测试:

import React from 'react';
import TestRenderer from 'react-test-renderer';
import Basic from './Basic';

describe('Basic', () => {
  test('renders', async done => {
    let component = TestRenderer.create(<Basic />);
    setImmediate(() => {
      expect(component.toJSON()).toMatchSnapshot();
      done();
    });
  });
});

当我运行时,它会生成以下笑话快照npm test

exports[`Basic renders 1`] = `
<div>
  <div>
    original
  </div>
</div>
`;

如何编写测试以便useEffect运行钩子并反映在快照中?所以生成的快照是这样的:

exports[`BasicClass renders 1`] = `
<div>
  <div>
    new1
  </div>
  <div>
    new2
  </div>
</div>
`;

这是不可能的吗,有没有我可以用来运行这个钩子的测试库?

4

1 回答 1

2

使用行为

import React from 'react';
import TestRenderer from 'react-test-renderer';
import Basic from './Basic';

describe('Basic', () => {
  test('renders', async () => {
    let component;
    await act(async () => {
      component = TestRenderer.create(<Basic />);
    });
    expect(component.toJSON()).toMatchSnapshot();
  });
});
于 2022-01-31T12:46:47.153 回答