I have UserContext
and a hook useUser
exported from src/app/context/user-context.tsx
.
Additionally I have an index.tsx file in src/app/context
which exports all child modules.
If I spyOn src/app/context/user-context
it works but changing the import to src/app/context
I get:
TypeError: Cannot redefine property: useUser at Function.defineProperty (<anonymous>)
Why is that?
Source code:
// src/app/context/user-context.tsx
export const UserContext = React.createContext({});
export function useUser() {
return useContext(UserContext);;
}
// src/app/context/index.tsx
export * from "./user-context";
// *.spec.tsx
// This works:
import * as UserContext from "src/app/context/user-context";
// This does not work:
// import * as UserContext from "src/app/context";
it("should render complete navigation when user is logged in", () => {
jest.spyOn(UserContext, "useUser").mockReturnValue({
user: mockUser,
update: (user) => null,
initialized: true,
});
})
UserContext
in the code being tested? If you're importing from "src/app/context/user-context", then you'll need to import it the same way in the spec file, or else it won't be mocking the same thing. Though your TypeError seems like a different issue... – Emporium