[英]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.