#Mocking a Fastify Request

1 messages · Page 1 of 1 (latest)

stray axle
#

I have a fastify multipart form request I'd like to unit test, and I really don't know where to start on mocking the request parameter in this code.

If anyone can point me in the right direction or provide some insight I'd be greatly appreciative. Thanks in advance!

neon notch
#

I'd rather not write unit tests for controller because a lot of things are handled by the fw prior calling controller's method, so you'll end up creating complex mocks

Instead, I'd write a integration test for this route

Or just an unit test for the business logic part

stray axle
#

I have most of the business logic mocked and unit tested already. I'm just trying to see how much unit testing coverage I can get as a personal point of pride.

vivid jetty
#

Well, looks like the request needs to have a file property that is a method, that returns an object with a toBuffer() method and a fields property. That seem about right?

stray axle
#

that seems like a correct understanding of the problem

vivid jetty
#

The "issue" is Typescript wanting to other properties of FastifyRequest, which is one of the reasons micalevisk suggested keeping it to an integration test. You could use a tool like @golevelup/ts-jest to create the entire object for you, subbing in the properties that you provide like

const req = createMock<FastifyRequest>({
  file: () => ({
    foBuffer: () => 'this is some buffer',
    fields: ['I', 'guess', 'an', 'array'],
  })
});

But some people don't like adding deps for single things.

stray axle
#

oooh. i'm already using golevelup for a few things. that might be a good solution

vivid jetty