1

I have a container class A which instantiates another class B:

class A {
        
    constructor(){
        this.initClassB()
    }

   private initClassB() : void{
        const options = {id : 0, ... etc}
        
        new B(options)        
   } 
}

In my test file, I instantiate the class A and I mock the class B:

import { mocked } from 'ts-jest/utils';
import { ClassA} from '../ClassA';
import { ClassB} from '../ClassB';

jest.mock('../ClassB');
const mockedClassB = mocked(ClassB, true);

describe('class B', () => {
    it('check if the minimum requirement are ok', () => {
      const { text, url } = ClassA.props.options;

      const expectedOptions = {
        event: ClassA.event,
        id: ClassA.getDefaultSiteId(),
        loadContent: () => '',
        loader: ClassA.loader,
        text: text,
        url: url,
      };

      
      // test fail whereas Expected/Received are identical
      expect(mockedClassB ).toHaveBeenCalledWith(expectedOptions)

      // fail with error : serialize to the same string
      expect(mockedCKTable.mock.calls[0][0]).toMatchObject(expectedOptions);
    });
  });

this is the error with the method toHaveBeenCalledWith:

enter image description here

this is the error with the method toMatchObject: enter image description here

And the dependency versions:

{ 
"@types/jest": "^26.0.24",
"ts-jest": "^27.0.4",
"jest": "^27.0.6",
"typescript": "~4.1.3",
 "@types/jest": "^26.0.24",
}

Where I am going wrong?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
rachOS
  • 93
  • 1
  • 7

1 Answers1

2

Asymmetric matchers doesn't works in this case: enter image description here

But! The test is green when I implement like this:

 const expectedOptions = {
        id: 0,
        // etc ...
      };

const mockEntries = Object.entries(mockedCKTable.mock.calls[0][0]);

const expectedEntries = Object.entries(expectedOptions);

expect(JSON.stringify(mockEntries)).toEqual(JSON.stringify(expectedEntries));
rachOS
  • 93
  • 1
  • 7