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

时间:2020-07-20 14:35:41

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

我有一个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);
  }
});

欢迎任何有帮助的建议..预先感谢!

1 个答案:

答案 0 :(得分:1)

您可以使用ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The identifier that starts with 'DMAnt[-] FLOAT(53) NULL, DMCst[-] FLOAT(53) N' is too long. Maximum length is 128. (103) (SQLExecDirectW)") 创建一个mock并覆盖对象原型上的方法:

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>"); }); }); 创建一个spy

jest.spyOn