How to test a function passed to another component? - reactjs

How do I write a unit test to cover the logic in fooFunction?
The logic could be moved out to another file in order to achieve test coverage, but what if I don't want to?
FooComponent.jsx:
import React, { useState } from 'react';
import FooContext from './FooContext';
import BarComponent from './BarComponent';
function FooComponent() {
const [value, setValue] = useState();
const fooFunction = inputValue => {
setValue(inputValue * 2);
};
return (
<div>
<span>Hello world!</span>
<BarComponent inputFunc={fooFunction} />
</div>
);
}
export default FooComponent;
How do I test it? Is the only option to not declare the function inside the FooComponent scope?

Related

React Hooks useContext value not updating

I'm updating a username based on a form input from another component. I put a console.log inside the provider component to make sure it's getting updated... it is! But the value never updates on the component receiving this value.
Here is the provider component:
import React, { useState, useContext } from 'react';
export const GetFirstName = React.createContext();
export const GetLastName = React.createContext();
export const SetUserName = React.createContext();
export const UserNameProvider = ({ children }) => {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
console.log(firstName);
return (
<SetUserName.Provider value={{ setFirstName, setLastName }}>
<GetFirstName.Provider value={firstName}>
<GetLastName.Provider value={lastName}>
{children}
</GetLastName.Provider>
</GetFirstName.Provider>
</SetUserName.Provider>
);
};
Account page (wraps the component with the provider so it can receive context):
import React, { useContext } from 'react';
import { useHistory } from 'react-router-dom';
import { GetLoggedIn, UserNameProvider } from '../Providers/providers.js';
import AccountHeader from './Account/AccountHeader.js';
import AccountItemsList from './Account/AccountItemsList.js';
import LoginModal from './Modal/LoginModal.js';
const Account = () => {
const history = useHistory();
const loggedIn = useContext(GetLoggedIn);
return !loggedIn ? (
<LoginModal closeModal={history.goBack} />
) : (
<div id='account-div'>
<UserNameProvider>
<AccountHeader />
</UserNameProvider>
<AccountItemsList /> // within AccountItemsList,
// another component is wrapped the same way
// to use setFirstName and setLastName
// this works fine, as the console.log shows
</div>
);
};
export default Account;
And finally the AccountHeader page, which receives only the initial value of '', then never reflects the current value after another component calls setFirstName.
import React, { useContext } from 'react';
import { GetFirstName } from '../../Providers/providers.js';
const AccountHeader = () => {
const firstName = useContext(GetFirstName);
return (
<div id='account-top'>
<img src='#' alt='User' />
<h1>{firstName}</h1>
</div>
);
};
Just to check my sanity I implemented a really simple version of this in a codepen and it works as it should. Elsewhere in my app I'm using context to check if the user is logged in. That is also working as it should. I've pulled almost all the hair out of my head.

ref.current is always undefined?

I need to use functional component ,so I can't use useRef directly. here is my code:
import React,{forwardRef,useImperativeHandle,useRef,useEffect} from "react";
import "./style.css";
export default function App() {
const ref_ = useRef();
useEffect(()=>{
console.log(ref_)
})
console.log(ref_)
return (
<div>
<Demo/>
</div>
);
}
const Demo = forwardRef((props,ref)=>{
useImperativeHandle(ref,()=>({
toggle(){
console.log(123);
}
}))
return(
<div ref={ref}>1234</div>
)
})
online code :
https://stackblitz.com/edit/forwardref-z68drh?file=src/App.js
and I want to trigger child component's function on parent component... can anyone help me?
You need to pass the ref itself to Demo component:
function App() {
const ref = useRef();
return <Demo ref={ref}/>;
}
Then you can use ref.current.toggle() due to useImperativeHandle.
https://stackblitz.com/edit/forwardref-z68drh-epz2xf?file=src/App.js

How to test code that uses a custom hook based on useContext with react-testing-library and jest

I've created a custom context hook - and I'm struggling to figure out how to pass values to its provider during testing.
My hook:
import React, { createContext, useContext, useState } from 'react';
const Context = createContext({});
export const ConfigurationProvider = ({ children }) => {
// Use State to keep the values
const [configuration, setConfiguration] = useState({});
// pass the value in provider and return
return (
<Context.Provider
value={{
configuration,
setConfiguration,
}}
>
{children}
</Context.Provider>
);
};
export const useConfigurationContext = () => useContext(Context);
export const { Consumer: ConfigurationConsumer } = Context;
This is how it's used in the application:
function App() {
return (
<ConfigurationProvider>
<div className="app">
<ComponentA />
</div>
</ConfigurationProvider>
);
}
And in ComponentA:
const ComponentA = () => {
// Get configuration
const configuration = useConfigurationContext();
return (
<div>{JSON.stringify(configuration)}</div>
)
}
This all works fine - considered that I'm calling setConfiguration from another component and set an object. Now for the testing part:
import React, { Component, createContext } from 'react';
import { render, waitFor } from '#testing-library/react';
import ComponentA from 'componentA';
const config = {
propertyA: 'hello',
};
test('renders the config', async () => {
const ConfigurationContext = createContext();
const { queryByText } = render(
<ConfigurationContext.Provider value={config}>
<ComponentA />
</ConfigurationContext.Provider>
);
expect(queryByText('hello')).toBeInTheDocument();
});
This doesn't work - I'm expecting the value that I'm sending in would be rendered in the div, but the context is an empty object. What am I doing wrong?
Thanks to Carle B. Navy I got the reason why it doesn't work. For other people two wonder what the solution is I fixed it by doing the following:
In my context hook, I changed the last line to export the provider as well:
export const { Consumer: ConfigConsumer, Provider: ConfigProvider } = Context;
Then in my test case, instead of creating a new context, I import the ConfigProvider at the top, and then:
const { queryByText } = render(
<ConfigProvider value={config}>
<ComponentA />
</ConfigProvider>
);
Thanks for helping me solve this and hope this helps someone else.

React custom hooks not working as expected

I am trying to implement a very simple custom hook called useOpen that simply returns a boolean (isOpen). I want to show or hide some text in App.js based on isOpen state. Currently, nothing is being rendered and trying to console.log(isOpen) in App.js gives me undefined. Thanks in advance!
App.js
import React from 'react'
import useOpen from './CustomHooks/useOpen'
function App () {
const {isOpen} = useOpen;
return (
<div className='App'>
{isOpen && <p>isOpen</p>}
</div>
)
}
export default App
useOpen.js
import { useState } from 'react'
export default function useOpen() {
const [isOpen, setIsOpen] = useState(true)
return { isOpen }
}
You’re missing the parens on useOpen. Should be useOpen().
const {isOpen} = useOpen; // missing ()
const {isOpen} = useOpen();
Try to call function useOpen at the component.
you need to execute the hook to get its value
and you don't need to put it in a object to deconstruct it on the other side
App.js
import React from 'react'
import useOpen from './CustomHooks/useOpen'
function App () {
//const {isOpen} = useOpen;
const isOpen = useOpen();
return (
<div className='App'>
{isOpen && <p>isOpen</p>}
</div>
)
}
export default App
useOpen.js
import { useState } from 'react'
export default function useOpen() {
const [isOpen, setIsOpen] = useState(true)
//return { isOpen }
return isOpen
}

Why am I getting "useContext is not a function" or "context is not defined"?

I am trying to use context in my stateless component. I updated my react to v16.8.0 and added useContext, however, I keep getting these two errors and don't know what else to do. Here is my code:
import React, { useState } from "react";
import axios from "axios";
import { LanguageContext } from "./languageContext";
import { useContext } from "react";
function StripeButton() {
const context = useContext(LanguageContext);
const stripe = Stripe("pk_live_5PjwBk9dSdW7htTKHQ3HKrTd");
const [error, setError] = useState();
const handleClick = () => {
stripe
.redirectToCheckout({
...
});
};
return (
<div>
<button
id="UrgentCheckedButtonYES"
className="btn-primary"
onClick={handleClick}
>
{this.context.main.name}
<br />
</button>
<div>{error}</div>
</div>
);
}
export default StripeButton;
StripeButton.contextType = LanguageContext;
You need to import useContext like this:
import { useContext } from 'react';
const { useContext } = React
useContext is exported as method property of React
(Tested this in React 18.)
In App.js File:
import { createContext } from "react";
import ChildComponent from "./components/ChildComponent";
export const Context = createContext("Default Value");
export default function App() {
const value = "My Context Value";
return (
<Context.Provider value={value}>
<ChildComponent />
</Context.Provider>
);
}
In ChildComponent.jsx file:
import { useContext } from "react";
import { Context } from "../App";
function ChildComponent() {
const value = useContext(Context);
return <h1>{value}</h1>;
}
export default ChildComponent;
You can have as many consumers as you want for a single context. If the context value changes,then all consumers are immediately notified and re-rendered.
If the consumer isn't wrapped inside the provider, but still tries to access the context value (using useContext(Context) or <Context.Consumer>), then the value of the context would be the default value argument supplied to createContext(defaultValue) factory function that had created the context.

Resources