标签: react-testing-library

使用react-query和axios测试React组件中的错误时出现问题。使用 React 测试库、Jest、msw 进行测试

我测试了一个反应组件,它应该显示旋转器、错误或获取的食谱列表。我设法测试该组件的加载以及何时成功获取数据。我遇到测试错误的问题。我使用 msw 创建了测试服务器,它具有返回错误的路由处理程序。我使用 axios 向服务器发出请求。我认为问题出在这里:axios 发出 3 个请求,直到最后一个响应 useQuery 返回 isLoading=true, isError=false。仅此后才返回 isLoading=false, isError=true。因此,在我的错误测试中, screen.debug() 显示微调器,并且 errorMessage 返回错误,因为它找不到带有文本“error”的渲染元素,该组件应该在发生错误时显示。对此我能做什么?我没有主意了。


编辑:

  • 我发现 useQuery 中有一个设置,“重试”,默认为 3 个请求。我仍然不知道如何处理测试中的组件重试请求。

我是反应测试和打字稿的新手。

来自 RecipeList.test.tsx:

import { setupServer } from 'msw/node';
import { rest } from 'msw';
import { QueryClient, QueryClientProvider, QueryCache } from 'react-query';

import RecipeList from './RecipeList';

const server = setupServer(
  rest.get(`${someUrl}`, (req, res, ctx) =>
    res(ctx.status(200), ctx.json(data))
  )
);

const queryCache = new QueryCache();
const RecipeListWithQueryClient = () => {
  const client = new QueryClient(); …
Run Code Online (Sandbox Code Playgroud)

mocking typescript reactjs react-testing-library msw

0
推荐指数
1
解决办法
1万
查看次数

如何使用react hooks测试库测试内部函数?

我有一个自定义钩子,我正在尝试编写使用 React hooks 测试库包的测试,我想知道如何测试未在自定义钩子中返回但在其他函数中使用的内部函数。

const customHook = () => {
  const [count, setCount] = React.useState(0);

  const doSomeThing = () => {
    ..code
  }

  const increment = () => {
    doSomeThing(); //Would like to make assertations on this
    setCount((x) => x + 1 );
  }

  return { count, increment }
}

export default customHook;
Run Code Online (Sandbox Code Playgroud)

测试

it('Should call increment', () => {
  const { result } = renderHook(() => useCustomHook())

  act(() => {
    result.current.increment();
  });

  expect(doSomeThing).toHaveBeenCalled(); //end result of what I would …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library react-hooks-testing-library

0
推荐指数
1
解决办法
2888
查看次数

如何在useEffect中使用axios请求测试react组件?

我已在 useEffect 中对功能组件做出反应。 https://codesandbox.io/s/nifty-dew-r2p1d?file=/src/App.tsx

const App = () => {
  const [data, setData] = useState<IJoke | undefined>(undefined);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  useEffect(() => {
    axios
      .get("https://v2.jokeapi.dev/joke/Programming?type=single")
      .then((res: AxiosResponse<IJoke>) => {
        setData(res.data);
      })
      .catch((err) => console.log(err))
      .finally(() => setIsLoading(false));
  }, []);

  return (
    <div className="App">
      {isLoading ? (
        <h2>Loading...</h2>
      ) : (
        <div className="info">
          <div className="info__cat">
            {data?.category ? `category: ${data.category}` : "bad category"}
          </div>
          <div className="info__joke">
            {data?.joke ? `joke: ${data?.joke}` : "bad data"}
          </div>
        </div>
      )}
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

如何通过测试覆盖组件?我需要在请求之前、及时和之后测试状态。在这种情况下如何模拟请求?

typescript reactjs jestjs axios react-testing-library

0
推荐指数
1
解决办法
5322
查看次数

React 中的 axios “无法在模块外部使用 import 语句”

我在 React 应用程序中使用 axios 以及 MUI 进行样式设置。我在开发时没有错误,但现在当我开始使用我的 React 应用程序编写测试时react testing libraryjest我收到 axios 模块错误,如下所示。我查阅了很多文章,很可能是因为 axios 将模块类型从 CommonJS 更改为 ECMAScript。我尝试在 React 中修改Vue.js 的这个解决方案,但我做不到。

\n
 FAIL  src/components/user/Contact.test.js\n  \xe2\x97\x8f Test suite failed to run\n\n    Jest encountered an unexpected token\n\n    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.\n\n    Out of the box Jest supports Babel, which will be …
Run Code Online (Sandbox Code Playgroud)

node.js reactjs jestjs react-testing-library

0
推荐指数
2
解决办法
5142
查看次数