One of my challenges is an endpoint responsible for user sign up:
import { createToken } './token'; // Unable to mock
import { sendEmail } './email'; // Unable to mock
export default async function signUp(
req: NextApiRequest,
res: NextApiResponse
): Promise<any> {
try {
// Generate a verification token
const token = await createToken(req.user);
// Email the token
await sendEmail(req.user, token);
return res.status(200).send({ done: true });
} catch (error: any) {
console.error(error);
return res.status(500).end(error.message);
}
}
I am wondering how I can properly mock these dependencies in my Jest unit tests:
import signup from './signup';
describe('signup', () => {
it('should return success', async () => {
const req: IncomingMessage = {} as unknown as IncomingMessage;
const res: ServerResponse = {
end: jest.fn(),
} as unknown as ServerResponse;
const actual = await signup(req, res);
...
});
});
Is it possible that nested dependencies cannot be mocked by Jest directly? Should I consider implementing a DI pattern in this endpoint? If so, what are some DI patterns that can support unit testing for Nextjs endpoints?