While testing my react application I run into a problem with creating file object in Jest/testing-library that would be attached to formData and over with request to check file upload to our service.
My logic is:
fetch(examplePDFurl).then((response) => {
response.blob().then(async (blob) => {
const file = await new File([blob], 'test.pdf', {
type: blob.type,
lastModified: new Date().getTime(),
})
await FileUploadService.upload(file)
.then((data) => {
//do stuff ...
})
})
})
where in the first step I am fetching a real blob data and then passing it off to a new File object constuctor. The service just takes the file and attaches it to formData:
const formatData = new FormData()
formatData.append('file', file)
However I'm getting a MIME error as if the file was missing the data and type.
Debugging shows that blob data was accurate:
Blob {
[Symbol(type)]: 'application/pdf',
[Symbol(buffer)]: <Buffer 25 50 44 46 2d 31 2e 33 0a 25 c7 ec 8f a2 0a 25 25 49 6e 76 6f 63 61 74 69 6f 6e 3a 20 70 73 32 70 64 66 20 2d 71 20 20 2d 64 4e 4f 50 41 55 53 45 20 ... 66328 more bytes>
}
size: 66378
But file was somewhat corrupted:
name: test.pdf
type: application/pdf
size: 13
All data from the PDF seems to be lost.
I was looking for solutions and found out that jest doesn't implement blob correctly and it can be patched with adding import 'blob-polyfill' to setupTests file, so I've added them:
-setupTests.ts
import '@testing-library/jest-dom/extend-expect'
import 'blob-polyfill'
export {}
and
-jest.config.js
const nextJest = require('next/jest')
const createJestConfig = nextJest({ dir: '.' })
const customJestConfig = {
testEnvironment: 'jsdom',
clearMocks: true,
moduleDirectories: ['node_modules', 'src'],
testPathIgnorePatterns: ['/cypress'],
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
}
module.exports = createJestConfig(customJestConfig)
Even with this workaround I'm still getting a MIME error and file object still seems to be empty.
my package related to test includes:
"typescript": "4.5.5"
"jest": "27.5.1",
"@types/jest": "27.5.1",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^12.1.5",
"@testing-library/user-event": "^14.0.0",
Is there a viable solution for creating a Pdf File object?