Jest: How to resolve TypeError from automock?

Created on 7 May 2016  路  1Comment  路  Source: facebook/jest

I have a simple test to instantiate a redis client using the auto mock. But I would get the following error. Not sure what I need to do?

TypeError: Cannot read property 'prototype' of undefined

import redis from 'redis';
describe('Test redis', () => {
    it('creates a mock redis client', () => {
        var client = redis.createClient('redis://localhost:6379');
    });
});

Most helpful comment

If you are trying to create a redis client that is mocked, you have to create a manual mock for it. Auto mocking can only go so far as to create automatic interfaces. When calling those functions, they will return undefined. However, you can implement custom implementations, like:

redis.createClient = jest.fn(() => {
  return a mock implementation here;
});

Note that the mock implementation depends on your needs and how full of a mock you'd like to create. Based on https://github.com/NodeRedis/node_redis#usage-example it has quite a few methods. Your mock could look something like this:

redis.createClient = jest.fn(() => {
  const client = {};
  client.on = jest.fn();
  client.set = jest.fn((key, value, print) => doSomethingOnSet());
  return client;
});

You might have to play a bit to get a good client to work but a good manual mock can be re-used in many tests.

>All comments

If you are trying to create a redis client that is mocked, you have to create a manual mock for it. Auto mocking can only go so far as to create automatic interfaces. When calling those functions, they will return undefined. However, you can implement custom implementations, like:

redis.createClient = jest.fn(() => {
  return a mock implementation here;
});

Note that the mock implementation depends on your needs and how full of a mock you'd like to create. Based on https://github.com/NodeRedis/node_redis#usage-example it has quite a few methods. Your mock could look something like this:

redis.createClient = jest.fn(() => {
  const client = {};
  client.on = jest.fn();
  client.set = jest.fn((key, value, print) => doSomethingOnSet());
  return client;
});

You might have to play a bit to get a good client to work but a good manual mock can be re-used in many tests.

Was this page helpful?
0 / 5 - 0 ratings