Jest always received undefined for ES6 imported class method

Viewed 107

I am just doing a dummy Jest test, it always says received: undefined.

Example:

/src/disjoint-set/index.ts

export default class DisjointSet {
  
  public foo() {
    return true;
  }
}

/src/disjoint-set/tests

import DisjointSet from '..';

describe('It tests Disjoint DataScture', () => {
  it('Should create a Disjoint Set', () => {
    const disSet = new DisjointSet();

    expect(disSet).toBeTruthy();

    expect(disSet.foo()).toBe(true);
  });
});

My console output:

src/data-structures/disjoint-set/tests/disjoint-set.test.ts It tests Disjoint DataScture ✕ Should create a Disjoint Set (5 ms)

● It tests Disjoint DataScture › Should create a Disjoint Set

expect(received).toBe(expected) // Object.is equality

Expected: true
Received: undefined

   7 |     expect(disSet).toBeTruthy();
   8 |
>  9 |     expect(disSet.foo()).toBe(true);
     |                          ^

  at Object.<anonymous> (src/data-structures/disjoint-set/__tests__/disjoint-set.test.ts:9:26)

My package.json

{
  "name": "leetcode",
  "version": "1.0.0",
  "description": "This is to test my data structure and algorithms in JavaScript",
  "main": "index.js",
  "scripts": {
    "test": "jest",
    "build": "tsc -p tsconfig.build.json"
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "keywords": [
    "leetcode",
    "javascript"
  ],
  "author": "",
  "license": "MIT",
  "bugs": {
    "url": ""
  },
  "homepage": "",
  "devDependencies": {
    "@types/jest": "^27.4.1",
    "jest": "^27.5.1",
    "ts-jest": "^27.1.4",
    "typescript": "^4.6.3"
  },
  "dependencies": {
    "node-fetch": "^2.6.7",
    "ts-node": "^10.7.0"
  }
}

My tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "types": ["node", "jest"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "baseUrl": ".",
    "noFallthroughCasesInSwitch": true,
    "outDir": "./dist",
    "jsx": "preserve"
  },
  "compileOnSave": true,
  "include": ["."]
}

My jest.config.ts

// jest.config.ts
import type { Config } from "@jest/types"

const config = {
  preset: "ts-jest",
  testEnvironment: "node",
  verbose: true,
  automock: true,
  testPathIgnorePatterns: ['/dist']
}
export default config;
1 Answers

In your class DisjointSet, public foo() {} should be foo() {}.

class DisjointSet {
  foo() {
    return true;
  }
}

const obj = new DisjointSet();
console.log(obj.foo());

Related