提问者:小点点

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


我有一个Signup函数,用于验证数据并检查是否存在。 我的功能运行良好。 我想测试我的注册函数,但不想执行内部函数。 相反,我想用不同的值来模拟它们,以覆盖不同的场景。 我是新的TS以及笑话和卡住,下面是我的代码和结构:

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
    }
  }
}

其他服务。ts:

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

其他服务2.ts

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

和我的测试文件:

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);
  }
});

欢迎提供任何帮助建议。 提前感谢!!


共1个答案

匿名用户

您可以使用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>");
  });
});

例如,如果您还需要验证mocked函数是用什么调用的,您还可以使用jest.spyon:

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