Я пытаюсь протестировать часть моей функции, связанную с обработкой ошибок, но я не уверен, как это сделать ... Я использую чей-то API, который всегда работает, так как я могу смоделировать API, который не подключается?
async function getElephant() {
const proxyurl = 'https://cors-anywhere.herokuapp.com/'
const url = 'https://elephant-api.herokuapp.com/elephants/random'
fetch(proxyurl + url)
.then((resp) => { return resp.json() })
.then((data) => {
data.forEach((elephant) => {
const { name, sex, species, note } = elephant
document.getElementById('name').value = name
document.getElementById('gender').value = sex
document.getElementById('species').value = species
document.getElementById('about').value = note
})
})
// .catch(() => console.log("Can't access " + url + " blocked?"))
.catch(() => ("Can't access"))
}
Мой тест:
test('Test .catch block, failure message to connect to url', async () => {
expect.assertions(1);
return expect(getElephant()).rejects.toEqual('Can't access');
})
, а также пытался использовать утилиту fetch-mock
test('Test .catch block, failure message to connect to url', async () => {
const url = 'https://lephant-api.herokuapp.com/elephants/random'; //Try misspelling url to catch error
fetchMock.get(url, {
status: 400,
body: JSON.stringify('BAD CONNECTION')
})
const response = await getElephant(url)
const result = await response.json()
expect(result).toThrow("Can't access")
})
Любые советы приветствуются!