我正在尝试使用ts-jest和testing-library/react运行一个测试,验证在执行登录函数时是否调用了localStorage.setItem函数。
下面是提供程序组件代码:
export const AuthProvider: FC<{ children: React.ReactNode }> = ({ children }) => {
const [authState, dispatch] = useReducer(AuthReducer, initialState, init);
const onLoginAction = (userLogged: User) => {
localStorage.setItem('user', JSON.stringify(userLogged));
dispatch({
type: AuthTypes.login,
payloads: userLogged
})
}
const onLogoutAction = () => {
//Something else
}
return (
<AuthContext.Provider value={{ authState, onLoginAction, onLogoutAction }}>
{children}
</AuthContext.Provider>
)
}
onLoginAction函数将数据保存到本地存储并执行一个分派。这是我的测试代码:
describe('testing AuthProvider', () => {
const initialState: stateProps = {
logged: false
}
test('should store user and change state to login', () => {
Storage.prototype.setItem = jest.fn();
const onLoginAction = jest.fn();
const onLogoutAction = jest.fn();
const context: contextProps = {
authState: initialState,
onLoginAction,
onLogoutAction,
}
const userLogged: User = {
username: 'Pepito123',
name: 'Pepito',
lastName: '',
githubUrl: ''
}
render(
<AuthContext.Provider value={context}>
<button aria-label='loginButton' onClick={() => onLoginAction(userLogged)}>login</button>
</AuthContext.Provider>
)
const button = screen.getByRole('button', { name: 'loginButton' }) as HTMLButtonElement;
fireEvent.click(button)
expect(onLoginAction).toHaveBeenCalledWith(userLogged);
expect(localStorage.setItem).toHaveBeenCalled(); //no reconoce que se esta llamando el localstorage (revisar luego)
})
})
控制台显示localStorage.setItem从未调用过. enter image description here
当执行fireEvent时。我希望onLoginAction内的所有代码都已执行(包括本地存储函数和调度)。我还需要在测试内执行其他内容吗?
1条答案
按热度按时间cld4siwp1#
你可以用jest spy来表示: