A.P
A.P

Reputation: 63

TypeError: Cannot read property 'prototype' of undefined + Jest + NodeJS

I am using jest for unit testing in of nodeJS APIs. I have installed jest and added it to the script in package.json as well. But facing the issue:

FAIL api/test/math.test.js ● Test suite failed to run

TypeError: Cannot read property 'prototype' of undefined

 at module.exports (node_modules/request-promise-core/configure/request2.js:34:48)
 at Object.<anonymous> (node_modules/request-promise-native/lib/rp.js:15:1)
 at Object.<anonymous> (node_modules/jsdom/lib/api.js:6:17)

 Test Suites: 1 failed, 1 total
 Tests:       0 total
 Snapshots:   0 total
 Time:        0.091s
 Ran all test suites.
 npm ERR! code ELIFECYCLE
 npm ERR! errno 1
 npm ERR! [email protected] test: `jest`
 npm ERR! Exit status 1
 npm ERR!
 npm ERR! Failed at the [email protected] test script.
 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Below are my sample classes for the same :

math.js :

  const sum = (a, b) => a + b
  const mul = (a, b) => a * b
  const sub = (a, b) => a - b
  const div = (a, b) => a / b

  export default { sum, mul, sub, div };

math.test.js :

 const  {sum, mul, sub, div}  = require("./math")

 test("Adding 1 + 1 equals 2", () => {
   expect(sum(1, 1)).toBe(2)
 })
 test("Multiplying 1 * 1 equals 1", () => {
   expect(mul(1, 1)).toBe(1)
 })
 test("Subtracting 1 - 1 equals 0", () => {
   expect(sub(1, 1)).toBe(0)
 })
 test("Dividing 1 / 1 equals 1", () => {
   expect(div(1, 1)).toBe(1)
 })

Any suggestions are appreciated. Thanks!

Upvotes: 3

Views: 5432

Answers (3)

Gagan Ganapathy
Gagan Ganapathy

Reputation: 67

q.js :

function sum(a, b) {
  return a + b;
}

module.exports = sum;

q.test.js :

const sum = require('../src/q');

test('adds 1 + 2 to equal 3', () => {
  const result = sum(1, 3);
  expect(result).toBe(3);
});

Even this gives an error, this is exactly copied from the jest documentation! https://jestjs.io/docs/en/getting-started

enter image description here

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Export uses import. module.exports will give you require.

Modules & Require

You should change math.js either:

module.exports = { sum, mul, sub, div };

For the code:

const {sum, mul, sub, div} = require("./math");

Import / Export

Or you should use:

import { sum, mul, sub, div } from "./math";

For the code:

export default { sum, mul, sub, div };

It's just the right combination.

Upvotes: 2

Elliot Lewis
Elliot Lewis

Reputation: 189

Change your exports in math.js to be:

module.exports = { sum, mul, sub, div };

NodeJS doesn't support the ES6 import/export syntax I believe.

Upvotes: 1

Related Questions