0

I have the following unit test which currently passes when it should fail (or rather I want it to fail)...

describe('getExchangeRate', function() {
    it('should return an error if the values entered are not currency ISO values', function(done) {
    done();
    expect(getExchangeRate('Pounds', 'Dollars', callBack())).to.throw(new Error('Input is not valid ISO code'));
    })
});

Here is the function I am testing...

function callBack(data) {
    return data;
}

function getExchangeRate(currencyFrom, currencyTo, callBack) {
  //connect to API url
  const exchangeRateRequest = http.get(`http://api.fixer.io/latest?base=${currencyFrom}`, response => {
    //read data
    let body = "";
    response.on('data', data => {
      body += data.toString();
    });
    response.on('end', () => {
      //parse data
      const exchangeRates = JSON.parse(body);
      //find exchange rate
      const exchangeRate = exchangeRates.rates[currencyTo];
      //return data
      callBack(exchangeRate);
    });
  });
}

I imagine that there is an error being thrown, since presumably there would be a 404, however in this case I want the test to fail as the message being returned would surely not be 'input is not a valid ISO code.'

I'm guessing there is something wrong with my test code. Anyway thanks in advance for any help.

I edited the code to include a callback after the feedback I received and although that was useful advice, that wasn't actually my question. The question is...why is the test passing? I want to test for a specific error message which this code is not providing. Thanks.

  • 1
    The problem not only in your test, but and in your code, `getExchangeRate` is implemented incorrectly, it calls async function, and newer returns a result. – alexmac Sep 03 '17 at 21:14
  • Well I'm quite new to this but it seems to work. It returns the exchange rate when the response ends. As I understand it. But any advice regarding this would be gratefully received. – Ed Southgate Sep 03 '17 at 21:18
  • You mean the return statement should be in the function not in the response? – Ed Southgate Sep 03 '17 at 21:19
  • 1
    I mean you need to use callback or Promise to pass the result of async function call. – alexmac Sep 03 '17 at 21:20
  • Ok useful advice. Just reading up on callbacks for async functions thanks. – Ed Southgate Sep 03 '17 at 21:29

0 Answers0