Skip to content

Testing fastify/multipart file upload without form-data library #1017

@shania-g

Description

@shania-g

Hello there.

I would like to add testing to my endpoint which uses fastify/multipart to accept a file upload and then writes it to the filesystem.

In the testing directory of this repository I saw that popular form-data library is used, however, I think this can also be achieved without it?

What I have come up with, but for some reason does not work:

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const filePath = join(__dirname, '../example.jpg')

describe('POST /asset', () => {
        it('should return 201 when the payload is valid', async () => {
            const rawData = readFileSync(filePath, 'binary')

            const body = new FormData()
            const blob = new Blob([rawData])

            body.set('file', blob, 'example.jpg')

            const res = await app.inject({
                method: 'POST',
                url: '/asset',
                payload: {
                    file: body.get('file')
                }
            })

            assert.deepStrictEqual(res.statusCode, 201)
        })
    })

However, this gives me the following error:

{"statusCode":400,"code":"FST_ERR_VALIDATION","error":"Bad Request","message":"body/file should be a file"}

This is my route definition (I do not think this is relevant, but maybe it could be):

fastify.post(
        '/',
        {
            schema: {
                consumes: ['multipart/form-data'],
                body: {
                    type: 'object',
                    required: ['file'],
                    properties: {
                        file: { isFile: true }
                    }
                }
            }
        },
        createAsset
    )

Is there any way to make this testing work?

Thank you very much in advance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions