如何用Typescript名称空间模拟模块? [英] How to mock a module with typescript namespace?

查看:44
本文介绍了如何用Typescript名称空间模拟模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是正在测试的功能:

import * as firebase from 'firebase';

function signInWithGoogle() {
  var provider = new firebase.auth.GoogleAuthProvider();
  firebase.auth().signInWithRedirect(provider);
}

firebase具有以下类型定义:

firebase has below type definition:

declare namespace firebase.auth 

function auth(app?: firebase.app.App): firebase.auth.Auth;

jest.mock('firebase', () => {
  // Don't know how to mock, what should be returned?  
})

我需要firebase的模拟firebase.auth.GoogleAuthProvider()firebase.auth()signInWithRedirect方法.

I need mock firebase.auth.GoogleAuthProvider(), firebase.auth() and signInWithRedirect methods of firebase.

但是firebase.auth可以是对象或函数. jest.mockfactory应该返回什么?

But the firebase.auth can be an object or a function. What should be returned in the factory of jest.mock?

jestjs是否支持这种模拟或间谍?谢谢大家.

Does jestjs support this kind of mock or spy? Thanks guys.

推荐答案

JavaScript函数是Function类型的对象.并且可以为每个对象分配属性,以便可以将其模拟为:

Javascript functions are objects of type Function. And to every object you can assign properties so you can mock it as:

jest.mock('firebase', () => {
  const auth = jest.fn();
  auth.GoogleAuthProvider = jest.fn();
  auth.Auth = jest.fn();
  return { auth };
});

或者您可以使用不带工厂功能的Jest自动模拟功能:

or you can use Jest's auto-mocking without factory function:

jest.mock('firebase');

然后模拟实现

// based on your question (not tested)
firebase.auth.mockImplementation(() => new firebase.auth.Auth())

这篇关于如何用Typescript名称空间模拟模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆