Jest : Mock object from another constructor

hi i have 2 classes Class A and Class B, class A constructor is instantiating class B in constructor

Class A has method hello, and Class B has method bye, Class A method hello calls Class B method bye, in my code coverage the class b method bye is not able to return null

have mocked class b

in a.js

import b from './b';

class A {
  //Main class from which other class is instantiated in constructor

  constructor() {
    this.b = new b();
  }

  hello() {
    let someval = this.b.bye(); //want to mock this bye function with null value

    if (someval) {
      console.log('success');
    } else {
      console.log('error'); // this line code coverage is not happening
    }
  }
}

in ./b

class B {
  bye() {
    //want to mock this method to return null
    console.log('Actual method call');
  }
}

in a.test.js

import a from './a';
import b from './b';

jest.mock('./b', () => {
  return jest.fn().mockImplementation(() => {
    return {
      bye: () => {
        return null;
      },
    };
  });
});

describe('Test A Hello', () => {
  const a = new a();

  beforeEach(() => {
    // Clear all instances and calls to constructor and all methods:
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  test('Get Token-Negative', async () => {
    a.hello();
  });
});

Expected result is Class a will call hello, which will call bye of Class b and since its mocked with null it will return null, but mocked bye method is not getting called

Answer

Can’t reproduce your issue. Your code works fine.

E.g.

a.js:

import b from './b';

export default class A {
  constructor() {
    this.b = new b();
  }

  hello() {
    let someval = this.b.bye();
    if (someval) {
      console.log('success');
    } else {
      console.log('error');
    }
  }
}

b.js:

export default class B {
  bye() {
    console.log('Actual method call');
  }
}

a.test.js:

import A from './a';

jest.mock('./b', () => {
  return jest.fn().mockImplementation(() => {
    return {
      bye: () => {
        return null;
      },
    };
  });
});

describe('Test A Hello', () => {
  const a = new A();

  test('Get Token-Negative', () => {
    a.hello();
  });
});

test result:

 PASS  examples/67196195/a.test.js (6.527 s)
  Test A Hello
    ✓ Get Token-Negative (15 ms)

  console.log
    error

      at A.hello (examples/67196195/a.js:13:15)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   85.71 |       50 |     100 |   85.71 |                   
 a.js     |   85.71 |       50 |     100 |   85.71 | 11                
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.049 s

The else branch is coveraged.