【发布时间】:2021-03-10 13:34:19
【问题描述】:
我最近遇到了这个奇怪的问题。我正在使用react-testing-library 并尝试进行简单的更新。每当用户输入正确的名称时,他们将获得 10 分,并将记录在屏幕上。但是,目前没有记录新分数(我保持默认分数为 0),并且我还收到错误消息:
Cannot log after tests are done. Did you forget to wait for something async in your test? Attempted to log "Warning: An update to Pokemon inside a test was not wrapped in act(...).
这就是我的测试代码的样子
//PokemonPage.test.js
test.only("should have their score updated if they guess the name correctly", async () => {
const guessedPokemon = "Pikachu";
jest.spyOn(global, "fetch").mockResolvedValue({
json: () =>
Promise.resolve({
name: "Pikachu",
sprites: {
other: {
"official-artwork": {
front_default:
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/25.png",
},
},
},
}),
});
render(<Pokemon pokemonTrainer={pokemonTrainer} />);
expect(screen.getByText(/Score: 0/)).toBeInTheDocument();
await waitFor(() => screen.findByRole("img"));
userEvent.type(await screen.findByRole("textbox"), guessedPokemon);
await waitFor(() => userEvent.click(screen.getByRole("button")))
expect(screen.getByText(/Score: 10/)).toBeInTheDocument()
});
这是它应该调用的代码:
//PokemonPage.js
const handleChange = (e) => setValue(e.target.value);
const handleSubmit = async (e) => {
e.preventDefault();
pokemonRef.current = await getPokemon();
setPokemonList((prev) => [
...prev,
{ name: pokemonRef.current.name, image: pokemonRef.current.image },
]);
updateScore(value)
setValue('')
};
const updateScore = async (guessedPokemonName) => {
if (guessedPokemonName === pokemonList[pokemonList.length - 1].name) {
setPokemonTrainerObject(prev => ({...prev, score: pokemonTrainerObject['score'] + 10 || 10 }))
}
};
基本上我正在提交用户输入,如果它是正确的guessedPokemonName === pokemonList[pokemonList.length - 1].name,那么用户对象将更新分数。这就是我试图用我的测试来模拟的。
我曾尝试使用waitFor,希望代码明白组件需要更新但无济于事。
有没有人遇到过类似的情况?
【问题讨论】:
标签: javascript unit-testing testing jestjs react-testing-library