【发布时间】: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