-
Question 💬I'm using v4, and my mock code is like this, but always gets undefined with useSession, does anyone mock useSession with v4 successful? I found a solution for v3 but does not work on v4 How to reproduce ☕️I have Header component like this import React from "react";
import { useSession, signOut } from "next-auth/react"
export default function Login() {
const {data: session, status} = useSession()
console.log({
session,
status
})
return (
<>
{session && ( <span>LOG OUT</span> )}
{!session && ( <span>LOG IN</span> )}
</>
);
} and test code like thisimport { 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();
})
}) and console.log always
Contributing 🙌🏽No, I am afraid I cannot help regarding this |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 9 replies
-
finally, I fixed it myself, it's because v4 change useSession return type to object {data: null, status: "authenticated}. so I changed by test code like this 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", () => {
const originalModule = jest.requireActual('next-auth/react');
const mockSession = {
expires: new Date(Date.now() + 2 * 86400).toISOString(),
user: { username: "admin" }
};
return {
__esModule: true,
...originalModule,
useSession: jest.fn(() => {
return {data: mockSession, status: 'authenticated'} // return type is [] in v3 but changed to {} in v4
}),
};
});
describe("Header Component", () => {
it('Show Log Out when has session',
async () => {
const {container} = render(<Header/>);
expect(container).toMatchSnapshot()
expect(screen.getByText("LOG OUT")).toBeInTheDocument();
})
}) |
Beta Was this translation helpful? Give feedback.
-
I had a slightly different version of the answer: import React from "react"
import { render, screen } from "@testing-library/react"
import { useSession } from "next-auth/react"
import Index from "../src/pages/index"
jest.mock("next-auth/react")
describe("Layout", () => {
it("renders correctly when signed out", async () => {
;(useSession as jest.Mock).mockReturnValueOnce({
data: {},
status: "unauthenticated",
})
render(<Index />)
expect(screen.getByText("Login"))
})
it("renders correctly when signed in", async () => {
;(useSession as jest.Mock).mockReturnValue({
data: {
user: {
username: "jeffrafter",
},
},
status: "authenticated",
})
render(<Index />)
const link = screen.getByRole("avatar")
expect(link).toHaveAttribute("href", "/@jeffrafter")
})
}) |
Beta Was this translation helpful? Give feedback.
-
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 |
Beta Was this translation helpful? Give feedback.
-
jest.mock('next-auth/react')
describe('Header Component', () => {
it('should be render sign out button when logged', () => {
const useSessionMocked = jest.mocked(useSession)
useSessionMocked.mockReturnValue({
data: {
user: {
name: 'johndoe',
},
expires: new Date(Date.now() + 2 * 86 * 1000).toISOString(),
},
status: 'authenticated',
update: jest.fn(),
})
const { getByRole } = render(<Header />)
const button = getByRole('button')
expect(button).toBeInTheDocument()
})
it('should be not render sign out button when not logged', () => {
const useSessionMocked = jest.mocked(useSession)
useSessionMocked.mockReturnValue({
data: null,
status: 'unauthenticated',
update: jest.fn(),
})
const { queryByRole } = render(<Header />)
const button = queryByRole('button')
expect(button).not.toBeInTheDocument()
})
}) It's my way of do test of next auth |
Beta Was this translation helpful? Give feedback.
-
Hello, I have some issues mocking next/auth, It says Cannot find module 'next-auth/react' from 'src/test/app/auth/loginForm.test.tsx': import { render, screen } from '@testing-library/react'
import "@testing-library/jest-dom";
import {LoginForm} from '@/app/auth/login/ui/loginForm'
import {useSession} from "next-auth/react";
jest.mock("next-auth/react", () => {
const originalModule = jest.requireActual('next-auth/react');
const mockSession = {
expires: new Date(Date.now() + 2 * 86400).toISOString(),
user: { name: "admin" }
};
return {
__esModule: true,
...originalModule,
useSession: jest.fn(() => {
return {data: mockSession, status: 'authenticated'}
}),
};
});
describe("Header Component", () => {
it('Show Log Out when has session',
async () => {
render(<LoginForm/>);
})
}) |
Beta Was this translation helpful? Give feedback.
finally, I fixed it myself, it's because v4 change useSession return type to object {data: null, status: "authenticated}. so I changed by test code like this