Reactjs Jest测试,如何为包含react钩子的方法编写测试?
我有一个简单的身份验证组件。我需要知道测试Reactjs Jest测试,如何为包含react钩子的方法编写测试?,reactjs,testing,jestjs,enzyme,next.js,Reactjs,Testing,Jestjs,Enzyme,Next.js,我有一个简单的身份验证组件。我需要知道测试isLogin方法的最佳方法是什么。我将用户的详细信息存储在redux存储中,每当调用此方法时,它都会检查存储并返回true或false。以下是组件: import React from 'react'; import type { Node } from 'react'; import { useSelector } from 'react-redux'; import { Render } from '..'; type componentProp
isLogin
方法的最佳方法是什么。我将用户的详细信息存储在redux存储中,每当调用此方法时,它都会检查存储并返回true或false。以下是组件:
import React from 'react';
import type { Node } from 'react';
import { useSelector } from 'react-redux';
import { Render } from '..';
type componentProps = {
fallback?: any,
children: Array<Node> | Node,
};
/* A method for checking if user is login or not */
const isLogin = () => {
const token = useSelector(state => state.User.token);
return !!token;
};
const Authentication = ({ fallback, children }: componentProps) => {
const token = useSelector(state => state.User.token);
return [
<Render key="item-auth-children" condition={token}>
{children}
</Render>,
<Render key="item-auth-fallback" condition={!token && fallback}>
{fallback}
</Render>,
];
};
Authentication.defaultProps = {
fallback: null,
};
Authentication.isLogin = isLogin;
export default Authentication;
从“React”导入React;
从“react”导入类型{Node};
从'react redux'导入{useSelector};
从“..”导入{Render};
类型componentProps={
撤退?:任何,
子节点:数组|节点,
};
/*检查用户是否登录的方法*/
常量isLogin=()=>{
const token=useSelector(state=>state.User.token);
返回!!令牌;
};
常量身份验证=({fallback,children}:componentProps)=>{
const token=useSelector(state=>state.User.token);
返回[
{儿童}
,
{回退}
,
];
};
Authentication.defaultProps={
回退:空,
};
Authentication.isLogin=isLogin;
导出默认身份验证;
我需要用jest-Ezyme编写一个测试来检查isLogin方法
我做了类似的事情,但没有任何意义:
import React from 'react';
import { mount } from 'enzyme';
import configureStore from 'redux-mock-store';
import { Provider } from 'react-redux';
import { Authentication } from '..';
const middleWares = [];
const mockStore = configureStore(middleWares);
const initialState = {
User: {
loading: false,
token: '',
userType: 'client',
error: {},
},
};
const store = mockStore(initialState);
describe('isLogin Method test', () => {
it('should checks user login state correctly', function() {
const wrapper = mount(
<Provider store={store}>{Authentication.isLogin()}</Provider>,
);
});
});
从“React”导入React;
从“酶”导入{mount};
从“redux模拟存储”导入configureStore;
从'react redux'导入{Provider};
从“..”导入{Authentication};
const middleware=[];
const mockStore=configureStore(中间件);
常量初始状态={
用户:{
加载:false,
令牌:“”,
用户类型:“客户端”,
错误:{},
},
};
常量存储=模拟存储(初始状态);
描述('isLogin方法测试',()=>{
它('应该正确检查用户登录状态',函数(){
常量包装器=装入(
{Authentication.isLogin()},
);
});
});
可能是相关的(显示如何使用模拟auth编写测试),即使它使用了Auth0,它也与您的案例非常相关:对itnext.io的引用不再有效。它使用的文件react-auth0-wrapper
在auth0示例应用程序中找不到。可能相关(显示如何使用模拟auth编写测试),即使它使用了auth0,它也与您的情况非常相关:对itnext.io
的引用不再有效。它使用的文件react-auth0-wrapper
在auth0示例应用程序中找不到。