GibboK
GibboK

Reputation: 73938

Jest Compared values have no visual difference. when testing arrays

I need to test an array returned from refExp using jest.

I am receiving this error:

Compared values have no visual difference

Currently I have a workaround and I am using JSON.stringify() within expect and toEqual, definitely sounds like a hack and I would like to know if I can fix it without it.

Any ideas is appreciated.

Demo: https://repl.it/repls/VictoriousCapitalProfile

const REG_EXP_CHECKBOX = /\$\$id=(\w+)(?:&description=(\w+))?\$\$([^$]*(?:\$(?!\$)[^$]*)*$)?/
describe('regExp', () => {
  it('should match REG_EXP_CHECKBOX', () => {
    expect('- [ ] $$id=uniq_id$$'.match(REG_EXP_CHECKBOX)).toEqual(
      ['$$id=uniq_id$$', 'uniq_id', undefined, undefined],
    )

    expect(['a', undefined]).toEqual(['a', undefined]);
  });
});

Upvotes: 0

Views: 2457

Answers (2)

Nikita Moshensky
Nikita Moshensky

Reputation: 51

You can use Array.from function that can create shallow-copied Array instance from an array-like or iterable object.

The code would look like this (demo):

const REG_EXP_CHECKBOX = /\$\$id=(\w+)(?:&description=(\w+))?\$\$([^$]*(?:\$(?!\$)[^$]*)*$)?/
describe('regExp', () => {
  it('should match REG_EXP_CHECKBOX', () => {
    expect(Array.from('- [ ] $$id=uniq_id$$'.match(REG_EXP_CHECKBOX) || [])).toEqual(
      ['$$id=uniq_id$$', 'uniq_id', undefined, undefined],
    )
  });
});

Upvotes: 1

Miguel Angel
Miguel Angel

Reputation: 983

Compare arrays is not so simple, because the 2 arrays are not equals, are different objects, with a different instance. So, you have 2 not equal arrays without any visual difference.

What you can do is split your response, and verify for each value, like this:

const add = require('./add');
const REG_EXP_CHECKBOX = /\$\$id=(\w+)(?:&description=(\w+))?\$\$([^$]*(?:\$(?!\$)[^$]*)*$)?/
describe('add', () => {
  it('should add two numbers', () => {
    const response = '- [ ] $$id=uniq_id$$'.match(REG_EXP_CHECKBOX);
    expect(response [0]).toEqual('$$id=uniq_id$$');
    expect(response [1]).toEqual('uniq_id');
    expect(response [2]).toBeUndefined();
    expect(response [3]).toBeUndefined();
  });
});

Here you're testing the response, and the string and undefined's will assert correctly.

Upvotes: 1

Related Questions