Fixing Jest error: Expected undefined to be ‘abc’.

If you write a test with Jest, you can get this puzzling error:

 FAIL  dist\__tests__\import-editions-test.js (0.058s)
● parseLine › it parses the header part of the line
  - Expected undefined to be 'abc'.
        at jasmine.buildExpectationResult (node_modules\jest-jasmine2\build\index.js:92:44)
        at Object.it (dist\__tests__\import-editions-test.js:7:52)
        at jasmine2 (node_modules\jest-jasmine2\build\index.js:294:7)
        at Test.run (node_modules\jest-cli\build\Test.js:50:12)
        at promise.then.then.data (node_modules\jest-cli\build\TestRunner.js:264:62)
        at process._tickCallback (internal\process\next_tick.js:103:7)

The cause of this is that the function is mocked, and is returning undefined. The reason for this is that you must import or require the module after you tell Jest not to mock it (Jest is inserting itself into require).

So, this does not work, but when you log the function you can see that it is mocked:

import { parseLine } from '../import-editions'

jest.unmock('../import-editions');
describe('parseLine', () => {
  it('parses the header part of the line', () => {
    console.log(parseLine);
    expect(parseLine('abc')).toBe('abc');
  });
});

Instead, this will work (you can also import the function within the test):

>
jest.unmock('../import-editions');

import { parseLine } from '../import-editions'

describe('parseLine', () => {
  it('parses the header part of the line', () => {
    expect(parseLine('abc')).toBe('abc');
  });
});

Leave a Reply

Your email address will not be published. Required fields are marked *