使用Mock in Jest测试在屏幕中呈现元素,并使用“findAllBy”方法找到它们

7rtdyuoh  于 2023-02-27  发布在  Jest
关注(0)|答案(1)|浏览(125)

所以基本上我尝试使用一个我用假数据做的模拟来测试一些组件。这一切都很好,但是当我尝试使用“findAllByRole”方法时,它只返回了一个空对象,并抛出一个错误,告诉我所有角色为“listitem”的项都不存在。
主部分测试js

import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import MainSection from './MainSection.js';
import { getItems } from '../../Database/Database.js';
import axios from 'axios';
import mockProducts from '../../Database/mockProducts.js';

jest.mock('axios');

beforeEach(() => {
    render(<MainSection />);
});

test('Check if renders all the 20 items in the MainSection', async () => {
    axios.get.mockResolvedValue({
        data: mockProducts,
    });

    await getItems();

    const allBoxes = screen.findAllByRole('listitem');

    expect(allBoxes).toHaveLength(20);
});

主要章节. js

import React, { useState, useEffect } from 'react';
import SearchBar from './SearchBar/SearchBar.js';
import FiltersBox from './FiltersBox/FiltersBox.js';
import { getItems } from '../../Database/Database.js';
import './MainSection.css';

function MainSection() {
    const [items, setItems] = useState([]);

    useEffect(() => {
        getItems().then(res => setItems(res));
    }, []);

    return (
        <section>
            <article className='items_container-main'>
                <div className='items_container' role='list'>
                    items.map(item => (
                            <div
                                className='item_box'
                                style={{ backgroundImage: `url(${item.image})` }}
                                key={item.id}
                                role='listitem'>
                                <div className='item_box-data_container'>
                                    <div className='item_box-data_container-price_star'>
                                        <div className='item_box-price'>${item.price}</div>
                                    <div className='item_box-title'>{item.title}</div>
                                </div>
                            </div>
                        ))}
                </div>
            </article>
        </section>
    );
}

export default MainSection;

数据库. js
错误

我的所有文件(如果需要)

我认为这就是错误的原因,因为我需要让测试使用带有虚假数据的模拟作为API响应数据,但我不知道如何才能做到这一点...

xdnvmnnf

xdnvmnnf1#

  • 您不需要使用jest.mock('axios')模拟整个axios模块,您可以只模拟axios.get()方法。
  • 您应该在模拟axios.get()之后呈现组件。
  • 您应该使用await screen.findAllByRole('listitem')waiting for appearance

MainSection.jsx

import React, { useState, useEffect } from 'react';
import { getItems } from './Database';

function MainSection() {
  const [items, setItems] = useState([]);
  console.log("🚀 ~ file: MainSection.jsx:6 ~ MainSection ~ items:", items)

  useEffect(() => {
    getItems().then((res) => setItems(res));
  }, []);

  return (
    <section>
      <article className="items_container-main">
        <div className="items_container" role="list">
          {items.map((item) => {
            return <div key={item.id} role='listitem'>{item.title}</div>;
          })}
        </div>
      </article>
    </section>
  );
}

export default MainSection;

MainSection.test.jsx

import React from 'react';
import { render, screen } from '@testing-library/react';
import MainSection from './MainSection';
import axios from 'axios';

test('Check if renders all the 20 items in the MainSection', async () => {
  const axiosGetSpy = jest.spyOn(axios, 'get').mockResolvedValue({
    data: [
      { id: 1, title: 'a' },
      { id: 2, title: 'b' },
    ],
  });
  render(<MainSection />);
  const allBoxes = await screen.findAllByRole('listitem');
  expect(allBoxes).toHaveLength(2);
  axiosGetSpy.mockRestore();
});

试验结果:

PASS  stackoverflow/75539392/MainSection.test.jsx (9.547 s)
  ✓ Check if renders all the 20 items in the MainSection (96 ms)

  console.log
    🚀 ~ file: MainSection.jsx:6 ~ MainSection ~ items: []

      at MainSection (stackoverflow/75539392/MainSection.jsx:6:11)

  console.log
    🚀 ~ file: MainSection.jsx:6 ~ MainSection ~ items: [ { id: 1, title: 'a' }, { id: 2, title: 'b' } ]

      at MainSection (stackoverflow/75539392/MainSection.jsx:6:11)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.348 s, estimated 12 s

相关问题