反应异步开玩笑没有按预期失败
React async jest not failing as intended
尽管在我的测试中改变了字符串和长度,它总是通过。它记录 console.log(false) 并通过测试。
这是测试
describe('newUsers', done => {
test('fetches the data from the API and correctly renders it', async () => {
render(<Input />)
setTimeout(async () => {
const items = await screen.findByPlaceholderText('Search...');
expect(items).toHaveLength(4);
done();
}, 100)
//screen.debug()
})
})
我正在尝试测试的呼叫
const [Loading, setLoading] = useState(false)
const [name, setName] = useState('');
const [options, setOptions] = useState([])
const [data, setData] = useState(false)
useEffect(() => {
setLoading(true)
const newUsers = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users')
.then((res) => res.json())
.then((data)=> {
setData(data)
});
};
newUsers();
}, [])
Html
return (
<div>
<div className='flex justify-center mt-10'>
<label>Name</label>
<input id="input" className='w-96 h-16 border-1 shadow-lg rounded-lg' placeholder="Search..."/>
发生这种情况是因为在测试完成后调用了异步代码。您可以查看 jest docs 以获得完整的解释。基本上,要修复它,您需要在测试函数中添加一个 done
参数,而不是不使用任何参数。这样,jest 将等到 done
被调用以完成测试:
describe('newUsers', () => {
test('fetches the data from the API and correctly renders it', async (done) => {
render(<Input />)
setTimeout(async () => {
const items = await screen.findByPlaceholderText('Search...');
expect(items).toHaveLength(4);
done();
}, 100)
//screen.debug()
})
})
尽管在我的测试中改变了字符串和长度,它总是通过。它记录 console.log(false) 并通过测试。
这是测试
describe('newUsers', done => {
test('fetches the data from the API and correctly renders it', async () => {
render(<Input />)
setTimeout(async () => {
const items = await screen.findByPlaceholderText('Search...');
expect(items).toHaveLength(4);
done();
}, 100)
//screen.debug()
})
})
我正在尝试测试的呼叫
const [Loading, setLoading] = useState(false)
const [name, setName] = useState('');
const [options, setOptions] = useState([])
const [data, setData] = useState(false)
useEffect(() => {
setLoading(true)
const newUsers = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users')
.then((res) => res.json())
.then((data)=> {
setData(data)
});
};
newUsers();
}, [])
Html
return (
<div>
<div className='flex justify-center mt-10'>
<label>Name</label>
<input id="input" className='w-96 h-16 border-1 shadow-lg rounded-lg' placeholder="Search..."/>
发生这种情况是因为在测试完成后调用了异步代码。您可以查看 jest docs 以获得完整的解释。基本上,要修复它,您需要在测试函数中添加一个 done
参数,而不是不使用任何参数。这样,jest 将等到 done
被调用以完成测试:
describe('newUsers', () => {
test('fetches the data from the API and correctly renders it', async (done) => {
render(<Input />)
setTimeout(async () => {
const items = await screen.findByPlaceholderText('Search...');
expect(items).toHaveLength(4);
done();
}, 100)
//screen.debug()
})
})