Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest Received: serializes to the same string on Object

newbie testing here and I ran into this error

module.js

import reducer from './reducer';

export default function getGModalModule({ domain }) {
  return {
    id: `GModal-module-${domain}`,
    reducerMap: {
      [domain]: reducer({
        domain,
      }),
    },
  };
}

module.test.js

import getGModalModule from '../module';
import reducer from '../reducer';

describe('getGModalModule', () => {
  it('returns the correct module', () => {
    const reducers = reducer({
      domain: 'demo'
    })

    const expectVal = getGModalModule({
      domain: 'demo'
    });
    const received = {
      id: `GModal-module-demo`,
      reducerMap: {
        demo: reducers,
      },
    }
    console.log("expectVal", expectVal)
    console.log("received", received)

    expect(expectVal).toEqual(received);
  });
});

The error says something like this:

Expected: {"id": "GModal-module-demo", "reducerMap": {"demo": [Function gModalReducer]}}
Received: serializes to the same string

I've tried to log out the result and they look exactly the same, any idea why this doesn't pass the test ?

expectVal { id: 'GModal-module-demo', reducerMap: { demo: [Function: gModalReducer] } }
received { id: 'GModal-module-demo', reducerMap: { demo: [Function: gModalReducer] } }

Thanks in advance,

like image 395
Duc Hong Avatar asked Oct 20 '25 18:10

Duc Hong


1 Answers

Jest cannot compare functions. Even if they are serialized into the same string, even if their source code is the same, function may refer to different variables through closures or bound to different this so we cannot say if functions are equal.

expect(function aaa() {}).toEqual(function aaa() {}); // fails

You may want to exclude methods before comparison explicitly or create custom matcher that will do that for you. But much better if you test what functions does instead. In your case you probably have separate test for ./reducer.js, right? You can just join both test: that one testing reducer in isolation and this one that checks object key names.

like image 143
skyboyer Avatar answered Oct 22 '25 07:10

skyboyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!