Thursday, 27 April 2017

Argument undefined while testing with mocha and chai

I'm building a Stock Price Checker project for freeCodeCamp on glitch now, an app which retrieves stock prices from google.finances and allows user to like stocks, but only permits 1 like per api. It also has functional tests written with Chai. Now, the project itself seems to work fine when I test it manually, but functional test won't pass (even though I'm sure the tests themselves are correct). Here's the problem: I have my handler function in a separate module, it gets called with req.query.stock as an argument. Here's parts of my code with console.logs in it: api.js

.get(function (req, res){
    console.log(req.query.stock, 'api');
    \\a callback function
    if (Array.isArray(req.query.stock)){
    stockHandler(req.ip, processing, req.query.stock[0], req.query.like);
    } else {
    stockHandler(req.ip, processing, req.query.stock, req.query.like);
   }

stockHandler.js:

module.exports = function(ip, callback, ticker, like)  {

  IP.findOne({address: ip}, function(err, found){
        if (err) return;
    console.log(ticker, 'findone');
        request({url: 'https://finance.google.com/finance/info?q=NASDAQ%3a' + ticker,
              json: true}, 
              function (error, response, body){     
      console.log(ticker, body);
       if (error) return;   
       var json = JSON.parse(body.slice(4, body.length));
      //other code

Now, I get an error because the first time Mocha runs my tests the ticker inside IP.findOne is undefined, and therefore the request to server comes back with response code 400 instead of data. This is what console logs ( ticker === 'goog', the second word is the marker of where console.log line is in the code):

  • goog api
  • undefined 'findone'
  • goog findone
  • undefined 'httpserver.cc: Response Code 400\n'

(Also sometimes undefined findone is before goog api, as if StockHandler.js was ran before api.js) But if I run my program manually, everything is fine:

  • goog api
  • goog findone
  • goog //response body

So, my question is - where does this undefined comes from? Why does it only occur with automated tests? And how do I get rid of it? Full code of my project is here: https://glitch.com/edit/#!/comfortable-mimosa I'd appreciate any help!



via Enk

No comments:

Post a Comment