用 Jest 模拟在工厂类中实例化的对象
我有一个看起来像这样的静态工厂方法:
export default class TheClientWrapper {
public static async buildClient(credentials: SomeCredentials): Promise<TheClient> {
const theClient = new TheClient(credentials);
await theClient.setup();
return theClient;
}
private constructor(credentials: SomeCredentials): {
// ...some construction
}
}
我这样做是因为,为了构建客户端,我 need 调用这个异步
setup
方法,我不能在构造函数中执行此操作,因为它是异步的。但是,我认为这是模拟客户端及其调用的一些麻烦的根源。
我不认为这个 Wrapper 类的调用者必须构造 and 调用
setup
方法,因为这要求他们对客户端实现了解得太多了。那么我该如何用 Jest 来模拟 theClient
?
回答如下: