-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to mock useSession? #775
Comments
Great question! I don't have an immediate answer for you (maybe somebody else will) but there are at least a couple of ways of mocking fetch in Jest and using that approach mock responses from |
Ok I managed to find a better way to mock it. Looks like I was overthinking it. I changed my test to this to get it working nicely: import React from "react";
import { render, screen, waitFor } from "@testing-library/react";
import Omega from "./Omega";
import client, { Session } from "next-auth/client";
import "@testing-library/jest-dom";
jest.mock("next-auth/client");
describe("Omega", () => {
it("Works", async () => {
const mockSession: Session = {
expires: "1",
user: { email: "a", name: "Delta", image: "c" },
};
(client.useSession as jest.Mock).mockReturnValueOnce([mockSession, false]);
render(<Omega />);
expect(screen.getByText("Hello, Delta")).toBeInTheDocument();
});
}); |
i did something similar. it would be great to get this added to the docs - perhaps near the cypress testing tutorial section?
|
I can also suggest https://mswjs.io/ |
Jest snapshot throws this error because window does not exist. To fix, I factored out a view, and snapshot that. useSession is passed as props: export default function Nav() {
const [session, loading] = useSession();
return <View session={session} loading={loading} />
} |
Im trying bot the answers from the initial fetch error and nothing seems to work for me in the test. Im receiving this:
And this is how i implemented it : Any help?
|
@danilockthar Were you able to fix this issue? I am too facing this same issue. |
@ajaykarthikr not really. I tried using msw and jest-fetch-mock with half of success, the error
|
@danilockthar I was able to mock useSession using msw. I took inspiration from this PR #1992. You can try the same. |
@ajaykarthikr can you share how you implemented it ? |
First I setup mock server to intercept rest api requests the NextAuth APIs. mock.js
Then in the Login Page I check if the page has been reloaded after login.
Everthing works fine, the For other pages that require authentication you just need to start the server before each jest unit test. |
I was receiving the same useSession.mockReturnValueOnce([false, false]); to this: useSession.mockReturnValue([false, false]); |
@cg-n Thanks! Your suggestion fixed my issue when I ran into this problem |
I'm using v4, and my mock code like this, but always get undefined with useSession, does anyone mock useSession with v4 successful ? import { render, screen } from '@testing-library/react'
import Header from '../../components/layout/Header'
import "@testing-library/jest-dom";
import {useSession} from "next-auth/react";
jest.mock("next-auth/react");
describe("Header Component", () => {
it('Show Log Out when has session',
async () => {
const mockSession = {
expires: new Date(Date.now() + 2 * 86400).toISOString(),
user: { username: "admin" }
};
(useSession as jest.Mock).mockReturnValueOnce([mockSession, 'authenticated']);
// @ts-ignore
// useSession.mockReturnValue([mockSession, 'authenticated']);
render(<Header/>);
expect(screen.getByText("LOG OUT")).toBeInTheDocument();
})
}) |
Hi, if interested, I wrote a package for mocking next-auth like: import { render, screen } from '@testing-library/react'
import { withMockAuth } from '@tomfreudenberg/next-auth-mock/jest';
import SignoutPage from '@/pages/auth/signoutx';
describe('Pages', () => {
describe('Signout', () => {
it('should render want to sign out', () => {
render(withMockAuth(<SignoutPage />, 'userAuthed'));
expect(screen.getByText('Do you want to sign out?'));
});
});
}); Find the whole story at: https://github.com/TomFreudenberg/next-auth-mock |
@agangdi I was able to do something like this: import { render, screen } from '@testing-library/react'
import MyPage from 'pages'
import userEvent from '@testing-library/user-event'
jest.mock('next-auth/react')
import { useSession, signIn, signOut } from 'next-auth/react'
const mockUseSession = useSession as jest.Mock
;(signIn as jest.Mock).mockImplementation(() => jest.fn())
;(signOut as jest.Mock).mockImplementation(() => jest.fn())
describe('My page', () => {
const renderMyPage = () => {
render(<MyPage />)
const signInButton = screen.queryByRole('button', {
name: 'Sign in with Provider',
})
const signOutButton = screen.queryByRole('button', {
name: 'Sign out',
})
return {
signInButton,
signOutButton,
}
}
it('renders when logged out', () => {
const user = userEvent.setup()
mockUseSession.mockReturnValue({
status: 'unauthenticated',
data: null,
})
const { signInButton, signOutButton } = renderMyPage()
expect(signInButton).toBeInTheDocument()
expect(signInButton).toHaveClass('usa-button')
expect(signOutButton).not.toBeInTheDocument()
await user.click(signInButton as HTMLElement)
expect(signIn).toHaveBeenCalledTimes(1)
expect(signIn).toHaveBeenCalledWith('cognito') // We're using cognito as the auth provider
})
} You can then also make use of UserEvent to verify that clicking on buttons calls the signIn/signOut mocked imports as well. Hope it helps! |
Your question
What's is the recommended way to mock useSession for unit tests with Jest and react testing library?
What are you trying to do
I have a component like this
and I wrote a test for it like this:
The test passes correctly except I get this error message in the console:
It looks like next-auth is trying to fetch the session through api even though I provided it in the provider. What's the recommended way to mock sessions in unit tests?
Feedback
Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.
The text was updated successfully, but these errors were encountered: