Duc Hong
Duc Hong

Reputation: 1179

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,

Upvotes: 4

Views: 14571

Answers (1)

skyboyer
skyboyer

Reputation: 23705

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.

Upvotes: 7

Related Questions