Jest /酶等待元素具有特定属性

问题描述 投票:0回答:1

[我正在用React创建一个天气应用,并用酶对其进行测试,在每次重新加载页面时以及在初始页面加载时,背景图像都应该更改/加载

App.js

function App() {
  const [background, setBackground] = useState('');


  async function fetchBgImage() {
    // getRandomImage returns a link fetched from the api
    setBackground(await getRandomImage());
  }

  useEffect(() => {
    fetchBgImage(); //a method which sets the background image and sets background to image url
  }, []);

  return (
    <div className="App">
      // Here backgound is just an image url
      <img id="background_image" src={background} alt="background image" />
    </div>
  );
}

在现实世界中,该应用程序运行正常,并且背景图像可以正确加载并在每个页面上重新加载,但是当我使用酶进行测试时,它不会等待设置backgound属性,因此,src属性为空。

App.test.js

beforeEach(() => {
  // I read that useEffect doesnt work with shallow rendering 
  // https://github.com/airbnb/enzyme/issues/2086
  jest.spyOn(React, 'useEffect').mockImplementation((f) => f());
});

it('displays background image', () => {
  const wrapper = shallow(<App />);
  const image = wrapper.find('#background_image');
  // src prop is empty
  console.log(image.props());
});

因此,如何使酶等待图像的src属性设置?

reactjs automated-tests jestjs enzyme
1个回答
0
投票

您可以编写一个辅助函数来等待该属性。类似于:

© www.soinside.com 2019 - 2024. All rights reserved.