简体   繁体   中英

TS Mock all nested functions using Jest

I've a signup function, which validates the data and check for existence. My functionality is all working fine. I wants to test my signup function, but don't want the internal functions to be executed. Instead I want to mock them with different values to cover different scenarios. I'm new to TS as well as Jest and stuck, Below is my code and structure:

service.ts:

import SomeOtherService from './someOtherService';
const somOtherService = new someOtherService();

import SomeOtherService2 from './someOtherService2';
const somOtherService2 = new someOtherService2();

export default class service {
  async signup(user: any): Promise<any> {
    const isValidData = await somOtherService.isValidData(user);      // mock return value for this function as boolean
    if(!isValidData) throw 'Invalid Data';
    const users = await somOtherService2.getUsers(user);          // mock return value for this function as array
    if(users.length) throw 'already exist';
    else {
      // insert in db and return        // mock return value for this function as object
    }
  }
}

someOtherService.ts:

export default class SomeOtherService {
  async isValidData(user){
      //some validations here
  }
}

someOtherService2.ts

export default class SomeOtherService2 {
  async getUsers(user){
      //fetching data from db
  }
}

and my test file:

import Service from '../service';
import MyOtherService from '../myOtherService';
import MyOtherService2 from '../myOtherService2';

const service = new Service();
const myOtherService = new MyOtherService();
const myOtherService2 = new MyOtherService2();

const user = {
  name: 'test',
  mobile: '12345678'
};

test('basic', async () => {
  try {
    // wants to mock all functions inside signup with default (different values for different scenarios) values
    const abc = await service.signup(user); 
    console.log('abc is => ', abc);
  } catch (e) {
    console.log('err ->', e.message);
  }
});

Any helps suggestions are welcome.. Thanks in advance !!

You can create a mock using jest.fn and overwrite the method on the object's prototype:

describe('test service', () => {
  it('should return ...', async () => {
    MyOtherService.prototype.isValidData = jest.fn().mockResolvedValue(true);
    MyOtherService2.prototype.getUsers = jest.fn().mockResolvedValue([{some:"data"}]);

    const abc = await service.signup(user); 
    expect(abc).toEqual("<tbd>");
  });
});

If, for example, you also need to verify what the mocked function was called with you can also create a spy using jest.spyOn :

const myOtherServiceSpy = jest.spyOn(MyOtherService.prototype, 'isValidData').mockResolvedValue(true);
...
expect(myOtherServiceSpy).toHaveBeenCalledTimes(1);

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