我正在尝试为我的组件编写一些单元测试。我对React还是很陌生,但是我正在使用上下文来管理组件之间的数据,但是我似乎无法将上下文传递给.test.js文件,因为它要么错误,要么快照返回且为空
这是一个示例组件:
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;
这是我的示例测试:
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();
});
任何帮助将不胜感激
答案 0 :(得分:0)
我假设SwapiProvider是呈现SwapiContext.Provider的组件,所以您尝试过:
const component = renderer.create(
<SwapiProvider>
<CharacterList /> //Need to figure out how to pass context to tests to this
</SwapiProvider>
);