Chris A
Chris A

Reputation: 1

React context and component testing

I am trying to write some unit tests for my components. I am fairly new to React but I am using context to manage the data between my components but I can't seem to pass context to my .test.js files as it either errors or the snapshot returns and empty

Here is an example component:

import React, { useContext } from 'react'
import {SwapiContext} from "../context/SwapiAPI";

const CharacterList = () =>{

    const swapiSearch = useContext(SwapiContext)

    function handleClick(character) {
        swapiSearch.setCharacter(character);
    }

    return(
        <div>
          {(swapiSearch.characters.length > 1) ? (
            <div className="sw-app-card">
                <p>We found multiple characters with your search, click on the name to display the profile.</p>
                <ul>
                {swapiSearch.characters.map((character) => (
                    <li key={character.id}><a href="javascript:void(0);" onClick={() => {handleClick(character)}}>{character.name}</a></li>
                ))}
                </ul>
            </div>
          ) : ""}
        </div>
    )
}

export default CharacterList;

And here is my example test:

import React from 'react';
import renderer from 'react-test-renderer';
import CharacterList from './CharacterList';
import SwapiProvider from "../context/SwapiAPI";

test('Test Character Card', () => {

    const component = renderer.create(
        <CharacterList /> //Need to figure out how to pass context to tests to this
    );

    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();

});

Any help would be appreciated

Upvotes: 0

Views: 253

Answers (1)

lissettdm
lissettdm

Reputation: 13078

I assume that SwapiProvider is a componente rendering SwapiContext.Provider, so did you try:

const component = renderer.create(
  <SwapiProvider>
    <CharacterList /> //Need to figure out how to pass context to tests to this
  </SwapiProvider>
);

Upvotes: 1

Related Questions