Reputation: 7971
I want to write test case for my router. I have const object which I want to mock during test case. How can I change the user object within the test file.
const user = {
isAuthenticated: true
};
export const PrivateRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props =>
user.isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
};
test.js
it("should return login route", () => {
const route = <PrivateRoute path="/" component={()=>{}} />
expect(route)..toMatchSnapshot();
});
it("should return home route", () => {
const route = <PrivateRoute path="/" component={()=>{}} />
expect(route)..toMatchSnapshot();
});
Upvotes: 0
Views: 2675
Reputation: 222369
user
should be available outside the module for testability purposes:
export const user = {
isAuthenticated: true
};
This way it can be mocked in tests
user.isAuthenticated = false;
Original value should be preserved in order to not cross-contaminate tests:
let originalIsAuthenticated;
beforeEach(() => {
originalIsAuthenticated = user.isAuthenticated;
});
afterEach(() => {
user.isAuthenticated = originalIsAuthenticated;
});
Upvotes: 2