Saurabh Saxena
Saurabh Saxena

Reputation: 117

Jest Test cases are failing for nodejs controller

When I am declaring a controller in node js like below all test cases are running fine.

 module.exports = (req,res) => {
    //code here 
  }

I am accessing the above controller like below in my test case file:

    const controller = require('filename')
    controller(req,res);

However, when I am declaring the same controller in node js like below all the test cases are getting failed.

const getController = (req,res) => {
//Code here 
}
module.exports = { getController }

I am accessing the above controller like below in my test case file:

const {getController } = require('filename');
getController (req,res);

Can someone please tell me what is happening here.

Upvotes: 0

Views: 262

Answers (1)

Omri Attiya
Omri Attiya

Reputation: 4037

It's not working because your syntax is wrong.

Use:

module.exports = { getController : getController }

and use it in 2 ways:

  1. import {getController} from 'filename';
  2. const getController = require('filename').getController

When you use require, you require a module, not a function of a module. When you use import, you are importing functions from a module.

You can read here about the differences between require and import

Upvotes: 1

Related Questions