简体   繁体   English

TS 使用 Jest 模拟所有嵌套函数

[英]TS Mock all nested functions using Jest

I've a signup function, which validates the data and check for existence.我有一个signup function,它验证数据并检查是否存在。 My functionality is all working fine.我的功能一切正常。 I wants to test my signup function, but don't want the internal functions to be executed.我想测试我的signup function,但不希望执行内部函数。 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:我是 TS 和 Jest 的新手并且卡住了,下面是我的代码和结构:

service.ts:服务.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: someOtherService.ts:

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

someOtherService2.ts 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:您可以使用jest.fn创建一个模拟并覆盖对象原型上的方法:

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 :例如,如果您还需要验证调用了模拟的 function 的内容,您还可以使用jest.spyOn创建一个间谍

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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