简体   繁体   中英

Jest mock for redis-sessions functions

I want to mock the redis-session function.

static async createSession(userData: string, userId: Uuid, ipAddress: string = 'NA'): Promise<string> {
try {
  const rs = this.getRedisConnection();
  return new Promise<string>((resolve, reject): void => {
    rs.create(
      {
        app: Configs.rsSessionApp,
        id: userId,
        ip: ipAddress,
        ttl: Configs.rsDefaultTtl,
        d: {
          data: userData,
        },
      },
      (err: object, resp: { token: string }): void => {
        if (resp !== undefined && resp.token.length > 0) {
          return resolve(resp.token);
        }

        if (err != null) {
          reject(err);
        }
      },
    );
  });
} catch (error) {
  return Promise.reject(error.message);
}

}

I want to make this line execute (err: object, resp: { token: string }): void => {} How to achieve or resolve this using jest unit test?. Another unit test to throw the error.

try...catch... cannot catch the exception of asynchronous code, you can remove it.

You can use jest.spyOn(object, methodName) to mock RedisSession.getRedisConnection() method and return a mocked redis connection. Then, mock the implementation of rs.create() method, you can get the anonymous callback function in your test case.

At last, call the anonymous callback function manually with mocked arguments.

Eg

index.ts :

import RedisSessions from 'redis-sessions';

interface Uuid {}

export class RedisSession {
  static async createSession(userData: string, userId: Uuid, ipAddress: string = 'NA'): Promise<string> {
    const rs = this.getRedisConnection();
    return new Promise<string>((resolve, reject): void => {
      rs.create(
        {
          app: 'test',
          id: userId,
          ip: ipAddress,
          ttl: 3600,
          d: {
            data: userData,
          },
        },
        (err: object, resp: { token: string }): void => {
          if (resp !== undefined && resp.token.length > 0) {
            return resolve(resp.token);
          }

          if (err != null) {
            reject(err);
          }
        }
      );
    });
  }

  static getRedisConnection() {
    return new RedisSessions({ host: '127.0.0.1', port: '6379', namespace: 'rs' });
  }
}

index.test.ts :

import { RedisSession } from './';

describe('67220364', () => {
  it('should create redis connection', async () => {
    const mRs = {
      create: jest.fn().mockImplementationOnce((option, callback) => {
        callback(null, { token: '123' });
      }),
    };
    const getRedisConnectionSpy = jest.spyOn(RedisSession, 'getRedisConnection').mockReturnValueOnce(mRs);
    const actual = await RedisSession.createSession('teresa teng', '1');
    expect(actual).toEqual('123');
    expect(getRedisConnectionSpy).toBeCalledTimes(1);
    expect(mRs.create).toBeCalledWith(
      {
        app: 'test',
        id: '1',
        ip: 'NA',
        ttl: 3600,
        d: {
          data: 'teresa teng',
        },
      },
      expect.any(Function)
    );
  });
});

unit test result:

 PASS  examples/67220364/index.test.ts (8.636 s)
  67220364
    ✓ should create redis connection (5 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |      70 |    57.14 |      75 |      70 |                   
 index.ts |      70 |    57.14 |      75 |      70 | 24-33             
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.941 s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM