![](/img/trans.png)
[英]firebase.auth().onAuthStateChanged not firing with Authorized domains
[英]How to test setState inside Firebase Auth onAuthStateChanged
我已经在AuthStateChanged上模拟了Firebase,所以测试工作完美,但我有这个用例,其中设置了用户:
const [isSignedIn, setIsSignedIn] = useState<boolean>(false);
const [displayName, setDisplayName] = useState<string | null>('');
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
console.log('OnAuthStateChanged USER', user);
if (user) {
setDisplayName(user.email);
setIsSignedIn(true);
} else {
setIsSignedIn(false);
setDisplayName('');
}
我知道您可以轻松地模拟它返回的内容,但如果可能的话,我不知道如何处理 function 的“内部”。
我需要专门设置 state,因为 DrawerNavigator 将根据用户是否登录显示不同的选项:
{isSignedIn && (
<>
<Drawer.Screen name='Dashboard' component={Dashboard} />
</>
)}
{!isSignedIn && (
<>
<Drawer.Screen name='Welcome' component={Welcome} />
<Drawer.Screen name='CreateAccount' component={CreateAccount} />
<Drawer.Screen name='Login' component={Login} />
</>
)}
我可以测试功能,但只能在默认的 state 上进行测试,因为它已初始化,我怎样才能使它工作? 或者我设置 state 的方式是否有任何其他变化,可以在其中进行测试?
这也是我现在的 mocking firebase/auth 模块:
/**
* Firebase
*/
jest.mock('firebase/auth', () => {
return {
getAuth: () => jest.fn(),
onAuthStateChanged: () => jest.fn(),
};
});
假设您要模拟登录用户时发生的延迟:
onAuthStateChanged
的回调。FirebaseAuth
实例的currentUser
属性应该同时更新。下面的模拟假设您一次不使用多个应用程序。 如果是这样,则必须实现获取特定的应用程序实例。
/**
* Firebase Auth Module
*/
jest.mock('firebase/auth', () => {
const authInstance = {
// while handshaking with the Firebase Auth servers, currentUser
// is null, regardless if someone is logged in or not.
currentUser: null
};
const mockedUserInfo = Object.freeze({ // force read-only
// mocked user info here - display name, email, etc
email: 'example@example.com'
});
// container for attached callbacks and state variables
const authChangeCallbacks = [];
let authCurrentUserInfo = mockedUserInfo;
let authTimer = null;
let authTimerCompleted = false;
// invoke all callbacks with current data
const fireOnChangeCallbacks = () => {
authMock.currentUser = authCurrentUserInfo;
callbacks.forEach((cb) => {
try {
cb(mockedUserInfo)); // invoke any active listeners
} catch (err) {
console.error('Error invoking callback', err);
}
});
authTimerCompleted = true;
}
authInstance.signOut = () => { // signInWithX will look similar to this
authCurrentUserInfo = null;
fireOnChangeCallbacks();
};
return {
getAuth: jest.fn(() => authInstance),
onAuthStateChanged: jest.fn((authMock, onChangeCallback) => {
if (!authTimer) {
// increase this delay to emulate slower connections
authTimer = setTimeout(fireOnChangeCallbacks, 2000);
}
callbacks.push(onChangeCallback);
const unsubscriber = () => {
const foundIndex = callbacks.indexOf(onChangeCallback);
if (foundIndex > -1) callbacks.splice(foundIndex, 1);
}
if (authTimerCompleted) {
// auth is "resolved" already, fire callback immediately
onChangeCallback(mockedUserInfo);
}
return unsubscriber;
})
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.