簡體   English   中英

TS 使用 Jest 模擬所有嵌套函數

[英]TS Mock all nested functions using Jest

我有一個signup function,它驗證數據並檢查是否存在。 我的功能一切正常。 我想測試我的signup function,但不希望執行內部函數。 相反,我想用不同的值模擬它們以涵蓋不同的場景。 我是 TS 和 Jest 的新手並且卡住了,下面是我的代碼和結構:

服務.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);
  }
});

歡迎任何幫助建議..提前謝謝!

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

例如,如果您還需要驗證調用了模擬的 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