How to correctly export and import functions for cypress plugin index.ts?

Viewed 958

I am developing plugin/index.ts file where I place async functions eg. clearing the database or uploading files to the app, but it starts to grow and I think about a way to keep it clean and structured.

In this video I see that there is a way to store functions in separate files and then export them using module.exports = { function } and then in the index.ts just import them using require.

But I can't have it working for my case.

This is a simplistic form of my plugins/index.ts file:

const uploadDocument = require('./documents');

module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config

  on('task', {
    clearDatabase: clearDatabase,
    uploadDocument: uploadDocument,
  });
  
  async function clearDatabase() { ... }
}

I decided to move the code of function uploadDocument to the plugins/documents.ts file:

enter image description here

and this is how the file plugins/documents.ts looks like:

imports...

async function uploadDocument(fileName: string) { ... }

module.exports = { uploadDocument }

And when I run the test with a task this way:

cy.task("uploadDocument", 'Very_light_file.pdf')

I get this error in Cypress:

enter image description here

3 Answers

From the post, I can tell TS is mixed JS there. The example is in JS, you're using TS, so there is no module.exports.

Try a pure JS version, then later convert it to TS.

It looks like the problem is with your module.exports and the import.

Try this,

// document.ts

export async function uploadDocument(fileName: string) { ... }
// module.exports = { uploadDocument }
// plugins/index.ts

import { uploadDocument } from './documents'
Related