Coder Social home page Coder Social logo

testing-react-query's People

Contributors

mitchelst avatar tkdodo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

testing-react-query's Issues

graphql tests

Would you please add an example for testing graphql?

Vitest Integration

Can you please do an example with the vitest library?

I am using vitest for testing. However, my tests do not return any outputs.

how to test a react component that invokes refetch

Hey there,

I am using this library in a project at work and we have a component that uses useQuery, which will invoke the refetch() function when a refresh button is clicked.

In my unit tests I'd like to verify that a re-fetch occurs by checking that our loading screen is shown, however since our loading screen is only shown if isFetching is true this fails. This is because after the initial fetch sets isFetching to false, it stays false even after calling refetch.

I've only seen examples of how to test this scenario when testing the custom hook that wraps useQuery, but I don't want to test the hook, I want to test the component that is ingesting it.

React Query Test with MSW - renderHook result.current always returns null

I am trying to test my react query hook using msw but renderHook's result's current value is always null. Why?

Note: the reason fetch does not include a URL is because this is a Rails Propshaft app and React and Rails apps share the same port.

In the real app, everything works and the hook returns data just fine but not in the test.

followed your original tutorial

reproducible sandbox

App.tsx

const App = () => {
	const {
		isLoading,
		data,
		error
	} = useFetchAccounts();

	if (isLoading) return "Loading...";

	if (error) return "An error has occurred: " + error;

	return (
		<div>
			{data?.map(item => (
				<div key={item.id}>{item.value}</div>
			))}
		</div>
	);
};

App.spec.tsx

const testQueryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: false
    }
  }
});

testQueryClient.setQueryDefaults(["accounts"], { retry: 5 });

describe("Accounts", () => {
  it("renders accounts", async () => {
    const { result } = renderHook(() => useFetchAccounts(), {
      wrapper: () => (
        <QueryClientProvider client={testQueryClient}>
          <App />
        </QueryClientProvider>
      )
    });

    console.log("result", result);
    await waitFor(() => expect(result.current.isSuccess).toBe(true));
  });
});

hooks.tsx

import { useQuery } from "@tanstack/react-query";

type FormattedAccount = {
  id: number;
  label: string;
};

const fetchAccount = async () => {
  const res = await fetch("/api/accounts");
  const accounts = await res.json();

  console.log("accounts", accounts);
  const formattedAccounts: FormattedAccount[] = [...accounts]?.map(
    (option) => ({
      id: option.id,
      label: option.name,
    })
  );

  console.log("formattedAccounts", formattedAccounts);
  return formattedAccounts;
};

export const useFetchAccounts = () => {
  return useQuery({
    queryKey: ["accounts"],
    queryFn: () => fetchAccount()
  });
};

server.ts

import { setupServer } from "msw/node";
import { rest } from "msw";

export const handlers = [
  rest.get("/api/accounts", (req, res, ctx) => {
    const rres = res(ctx.status(200), ctx.json([{ id: 1, name: "Account 1" }]));
    console.log("rres", rres);
    return rres;
  })
];

export const server = setupServer(...handlers);

jest.config.js

/** @type {import('ts-jest').JestConfigWithTsJest} */

module.exports = {
  preset: "ts-jest",
  collectCoverage: true,
  collectCoverageFrom: ["src/**/*.spec.{ts, tsx}"],
  coverageDirectory: "coverage",
  testEnvironment: "jsdom",
  setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
  transform: {
    "^.+\\.(ts|tsx)?$": "ts-jest"
  }
};

jest.setup.ts

import "@testing-library/jest-dom";
import "whatwg-fetch";
import { server } from "./server";

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

export default global.matchMedia =
  global.matchMedia ||
  function (query) {
    return {
      matches: false,
      media: query,
      onchange: null,
      addListener: jest.fn(), // deprecated
      removeListener: jest.fn(), // deprecated
      addEventListener: jest.fn(),
      removeEventListener: jest.fn(),
      dispatchEvent: jest.fn()
    };
  };

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.