【问题标题】:TS Mock all nested functions using JestTS 使用 Jest 模拟所有嵌套函数
【发布时间】:2020-07-21 03:35:34
【问题描述】:

我有一个signup 函数,它验证数据并检查是否存在。我的功能一切正常。我想测试我的signup 函数,但不希望执行内部函数。相反,我想用不同的值模拟它们以涵盖不同的场景。我是 TS 和 Jest 的新手并且卡住了,下面是我的代码和结构:

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

还有我的测试文件:

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

欢迎任何帮助建议..提前致谢!!

【问题讨论】:

    标签: node.js typescript unit-testing mocking jestjs


    【解决方案1】:

    您可以使用jest.fn 创建mock 并覆盖对象原型上的方法:

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

    例如,如果您还需要验证调用了什么模拟函数,您还可以使用jest.spyOn 创建一个spy

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

    【讨论】:

    • 感谢您的解决方案,就像一个魅力.. 非常感谢 :)
    • 乐于助人,请采纳答案。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2019-08-19
    • 2021-09-07
    • 2021-04-01
    • 2020-06-21
    • 2017-10-26
    相关资源
    最近更新 更多