Home > Software engineering >  Typescript import module.exports sub function
Typescript import module.exports sub function

Time:10-21

I'm using mocha to test a function and I'm facing an error while running the test file.

The file structure is as follows

server
|-test
|  |-customer.test.ts
|-customer.js

This is the customer.js file function

module.exports = (instance) => {
   instance.validate = async (ctx) => {
      // some code here 
   }
}

This is the mocha test case file customer.test.ts

const instance =  require("../customer")

/* eslint-disable no-undef */
describe('customer', () => {
  describe('/POST customers', () => {
    it('Create Buy customer', (done) => {
      instance.validate({        
      })
      done();

    });
  })
});

But when I run the file using the command mocha .\customer.test.ts it shows me the following error

TypeError: instance.validate is not a function

How do I make the above function execute?

CodePudding user response:

What you're exporting and what you're doing with the import don't match. The problem is (probably) the export. What you have is this:

module.exports = (instance) => {
   instance.validate = async (ctx) => {
      // some code here 
   }
}

That exports a function that, when called, will add a validate method to the object that you pass to it. It does not export an object with a validate method, that would look like this:

module.exports = {
   validate: async (ctx) => {
      // some code here 
   },
};

So you need to either fix the export (which I suspect is the problem), or (if the export is really meant to do that), test what it actually does by passing in an object and then checking that, after the call, the object has a validate method.

  • Related