JestJS: How to get different results from the promise of a mocked function and check for an abandoned error?

I need to check a function ( example()) that uses another ( validateDataset). Since I only want to test the function example(), I am mocking validateDataset().

Of course, each test needs a different result from the mocking function. But how do I set different promise results for the funded feature? In my attempt, shown below, the bullying function always returns the same value.

So, in this example, I cannot verify the abandoned error.

functions.js

import { validateDataset } from './helper/validation'

export async function example (id) {
  const { docElement } = await validateDataset(id)
  if (!docElement) throw Error('Missing content')
  return docElement
}

functions.test.js

import { example } from './functions'

jest.mock('./helper/validation', () => ({
  validateDataset: jest.fn(() => Promise.resolve({
    docMain: {},
    docElement: {
      data: 'result'
    }
  }))
}))

describe('example()', () => {
  test('should return object', async () => {
    const result = await example('123')
    expect(result.data).toBe('result')
  })
  test('should throw error', async () => {
    const result = await example('123')
    // How to get different result (`null`) in this test
    // How to test for the thrown error?
  })
})
+6
source share
2 answers

Jest, , , , , , , .

, , validateDataset . .

import { example } from './example';
import { validateDataset } from './helper/validation';

// Declare export of './helper/validation' as a Mock Function.
// It marks all named exports inside as Mock Functions too.
jest.mock('./helper/validation');

test('example() should return object', async () => {
  // Because `validateDataset` is already mocked, we can provide
  // an implementation. For this test we'd like it to be original one.
  validateDataset.mockImplementation(() => {
    // `jest.requireActual` calls unmocked module
    return jest.requireActual('./helper/validation').validateDataset();
  });
  const result = await example('123');
  expect(result.data).toBe('result');
});

test('example() should throw error', async () => {
  // Worth to make sure our async assertions are actually made
  expect.assertions(1);
  // We can adjust the implementation of `validateDataset` however we like,
  // because it a Mock Function. So we return a null `docElement`
  validateDataset.mockImplementation(() => ({ docElement: null }));
  try {
    await example('123');
  } catch (error) {
    expect(error.message).toEqual('Missing content');
  }
});

, .

+1

Rewire function.js.

functions.test.js :

import * as rewire from 'rewire';
const functionsModule = rewire('functions.js');

describe('example()', () => {
    var functionsModule;

    test('should return object', done => {
        functionsModule.__set__('validateDataset', () => {
            Promise.resolve({
                docMain: {},
                docElement: {
                    data: 'result'
                }
            })
        });
        functionsModule.example('123').then(result => {
            expect(result.docElement.data).toBe('result');
            done(); 
        });

    })

    test('should throw error', done => {
        functionsModule.__set__('validateDataset', () => {
            return Promise.reject();
        });
        functionsModule.example('123').catch(done);
    });

})
0

All Articles