JEST Testing try catch - получить сообщение об ошибке - PullRequest
0 голосов
/ 17 июня 2020

Я пытаюсь протестировать часть моей функции, связанную с обработкой ошибок, но я не уверен, как это сделать ... Я использую чей-то 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")
})

Любые советы приветствуются!

1 Ответ

0 голосов
/ 17 июня 2020

Надеюсь, этот пример поможет вам обрабатывать ошибки с помощью try catch

function addTask() {

  x = "test input";
  	
  try { 
    if(x == "")  	throw "empty";          // error cases
    if(isNaN(x)) 	throw "not a number";
      x = Number(x);
    if(x > 10)   	throw "too high";
  }
  catch(err) {                          // if there's an error
    console.error("Input is " + err);   // write the error in console
	}
	finally {								    // Lets you execute code, after try and catch, regardless of the result
		 console.log("Done");              
	}
}

addTask();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...