0

Hi is to possible to set a mocked property to undefined somehow?

Interface I want to mock:

export interface IEmail {
  from: string | undefined;
  body: string;
  to: string;
}

Code I want to test:

async function sendEmail(emailData: IEmail): Promise<void> {
  await this.send({
    emailBody: emailData.body,
    emailBodyFrom: emailData.from || "default_email@mail.com",
    emailTo: emailData.to,
  });
}

The test:

import { mock } from 'jest-mock-extended';


it('should send email', async () => {
    const options = mock<IEmail>({});
  options.from = undefined
  options.to = 'jane.doe@gmail.com'
  mockemailService.send.mockResolvedValueOnce("");
  await emailService.sendEmail(options);
  expect(mockemailService.send).toHaveBeenCalledWith({
    from: 'default_email@mail.com',
    to: 'jane.doe@gmail.com',
  });
});

I expect this the send function to have been called with default_email@mail.com but instead it has been called with a mock function causing the test to fail. How can I forcefully set the property from to undefined?

Hugo
  • 135
  • 2
  • 9
  • Why is that a mock at all? Just pass a regular object. – jonrsharpe Dec 21 '22 at 07:50
  • Hi, thank you for you reply. This is just an example, the actual interface is much much bigger hence the reason for me to mock it instead of assigning mock data to every field. – Hugo Dec 21 '22 at 15:06
  • Then you might want to rethink the design, e.g. apply the interface segregation principle. It should be easy enough to write functions like `createThing(relevant: Partial): Thing`. – jonrsharpe Dec 21 '22 at 15:08

0 Answers0