4

I have TypeScript setup and I am testing an endpoint that takes FormData as an input and uses multer to process the multipart data (pdf file); it looks like this:

app.post("/v1/sources/send-email", 
  upload.single('file'),
  handledEmail
);

My jest test has a post request that passes dummy formData to it in the send method, it looks like this:

import FormData from 'form-data';
    ...
    const response = await request(app)
      .post("/v1/sources/send-email")
      .send(formData)
      .set("X-AUTH-TOKEN", validToken);

However, when I try to create formData like the following, I get an error:

let formData = new FormData();
formData.append('file', fs.createReadStream('path/to/file.pdf'));

The error is:

Argument of type 'ReadStream' is not assignable to parameter of type 'string | Blob'.

Any ideas on how I can get this PDF file on this formData variable, so I can pass it to the test's post request?

My tsconfig.json looks like the following:

{
  "compilerOptions": {
    "allowJs": false,
    "baseUrl": ".",
    "esModuleInterop": true,
    "lib": ["DOM", "ES2018"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "noUnusedLocals": true,
    "outDir": "dist",
    "paths": {
      "*": [
        "src/main/ts/*",
        "node_modules/*"
      ]
    },
    "sourceMap": true,
    "target": "es6"
  },
  "include": ["src/main/ts/**/*"]
}

I saw someone here say that creating a function to mock FormData might work, but when I do the following, there is an error in the global assignment:

function FormDataMock() {
  this.append = jest.fn();
}
global.FormData = FormDataMock();

The error says Property 'FormData' does not exist on type 'Global'.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
thehme
  • 2,698
  • 4
  • 33
  • 39
  • Is this is a typescript compilation error you're getting? Can you share your TS config and the type definitions you're using, if any? – shkaper Sep 05 '19 at 23:48
  • @shkaper yes, this is a TS setup and I think my main issue is how to mock the expected `FormData`, so I can pass it in the `send` command to the `post` request. – thehme Sep 06 '19 at 11:55

0 Answers0