Hellp please, i've been stuck for days

Please i need help to pass these tests ,

  1. The stockData property includes the stock symbol as a string, the price as a number, and likes as a number.
  2. All 5 functional tests are complete and passing.
    what am i doing wrong please.

I’m working on this project in my local machine, i’ve not uploaded it on github yet
The env file

PORT=3000
DB = mongodb+srv://Faytey:angela070@cluster0.ljzjs.mongodb.net/db1?retryWrites=true&w=majority
# NODE_ENV=test

The db file

const mongoose = require('mongoose');
const db = mongoose.connect(process.env.DB, { useNewUrlParser: true, useUnifiedTopology: true });

module.exports = db;

The schema

const mongoose = require('mongoose');
const stockSchema = mongoose.Schema({
  symbol:  {type: {type: String, require: true}},
    likes: {type: {type: [String]}, default: 0}
  });

  const Stock = mongoose.model("Stock", stockSchema);
  exports.Stock = Stock;

The server

'use strict';
require('dotenv').config();
const express     = require('express');
const bodyParser  = require('body-parser');
const cors        = require('cors');

const apiRoutes         = require('./routes/api.js');
const fccTestingRoutes  = require('./routes/fcctesting.js');
const runner            = require('./test-runner');
const helmet = require('helmet')

require("./db-connections");

const app = express();

app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "https://code.jquery.com/jquery-2.2.1.min.js"],
      styleSrc: ["'self'"],
    },
  })
);

app.use('/public', express.static(process.cwd() + '/public'));

app.use(cors({origin: '*'})); //For FCC testing purposes only

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

//Index page (static HTML)
app.route('/')
  .get(function (req, res) {
    res.sendFile(process.cwd() + '/views/index.html');
  });

//For FCC testing purposes
fccTestingRoutes(app);

//Routing for API 
apiRoutes(app);  
    
//404 Not Found Middleware
app.use(function(req, res, next) {
  res.status(404)
    .type('text')
    .send('Not Found');
});

//Start our server and tests!
const listener = app.listen(process.env.PORT || 3000, function () {
  console.log('Your app is listening on port ' + listener.address().port);
  if(process.env.NODE_ENV==='test') {
    console.log('Running Tests...');
    setTimeout(function () {
      try {
        runner.run();
      } catch(e) {
        console.log('Tests are not valid:');
        console.error(e);
      }
    }, 3500);
  }
});

module.exports = app; //for testing

App.js

'use strict';
const StockModel = require("../model").Stock;
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

async function createStock(stock, like, ip){
const newStock = new StockModel({
  symbol: stock,
  likes: like ? (ip) : [],
});
const savedNow = await newStock.save();
return savedNow;
}

async function findStock(stock){
  return await StockModel.findOne({symbol:stock}).exec();
}

async function saveStock(stock, like, ip){
  let saved = {};
  const foundStock = await findStock(stock);
  if(!foundStock){
    const createsaved = await createStock(stock, like, ip);
    saved = createsaved;
    return saved;
  } else {
    if(like && foundStock.likes.indexOf(ip) === -1){
      foundStock.likes.push(ip);
    }
    saved = await foundStock.save();
    return saved;
  }
}

async function getStock(stock) {
  const response = await fetch(
  'https://stock-price-checker-proxy.freecodecamp.rocks/v1/stock/${stock}/quote'
)

const {symbol, latestPrice} = await response.json();
return {symbol, latestPrice};

}

module.exports = function (app) {
  //https://stock-price-checker-proxy.freecodecamp.rocks/v1/stock/goog/quote
  app.route('/api/stock-prices')
    .get(async function (req, res){
      const {stock, like} = req.query;
      if(Array.isArray(stock)){
        console.log("stocks", stock);

        const {symbol, latestPrice} = await getStock(stock[0]);
        const {symbol: symbol2, latestPrice: latestPrice2} = await getStock(stock[1]);

        const firstStock = await saveStock(stock[0, like, req.ip]);
        const secondStock = await saveStock(stock[1, like, req.ip]);

        let stockData = [];
        if(!symbol){
          stockData.push({
            rel_likes: firstStock.likes.length - secondStock.likes.length,
          });
        } else{
            stockData.push({
              stock: symbol,
              price: latestPrice,
              rel_likes: firstStock.likes.length - secondStock.likes.length,
            })
        }

        if(!symbol2){
          stockData.push({
            rel_likes: firstStock.likes.length - secondStock.likes.length,
          });
        } else{
            stockData.push({
              stock: symbol2,
              price: latestPrice2,
              rel_likes: firstStock.likes.length - secondStock.likes.length,
            })
        }
          res.json({
            stockData
          })
          return;
        }
        
      const {symbol, latestPrice} = await getStock(stock);
      if(!symbol){
        res.json({stockData: {likes: like ? 1 : 0}});
        return;
      }

      const oneStockData = await saveStock(symbol, like, req.ip);
      console.log("One Stock Data", oneStockData);
      
      res.json({
        stockData: {
          stock: symbol,
          price: latestPrice,
          likes: oneStockData.likes.length,
        },
      })
    });
  
}

Functional tests

const chaiHttp = require('chai-http');
const chai = require('chai');
const assert = chai.assert;
const server = require('../server');

chai.use(chaiHttp);

suite('Functional Tests', function() {
    suite("5 functional get request tests", function () {
        test("Viewing one stock:", function (done) {
            chai
            .request(server)
            .get("/api/stock-prices/")
            .set("content-type", "application/json")
            .query({stock: "GOOG"})
            .end(function(err,res){
                assert.equal(res.status, 200);
                assert.property(res.body, "stockData");
                assert.equal(res.body.stockData.stock, "GOOG");
                assert.exists(res.body.stockData.price, "GOOG has a price");
                done();
            });
        });
        test("Viewing one stock and liking it:", function (done) {
            chai
            .request(server)
            .get("/api/stock-prices/")
            .set("content-type", "application/json")
            .query({stock: "TSLA", like: true})
            .end(function(err,res){
                assert.equal(res.status, 200);
                assert.property(res.body, "stockData");
                assert.equal(res.body.stockData.stock, "TSLA");
                assert.equal(res.body.stockData.likes, 1);
                assert.exists(res.body.stockData.price, "TSLA has a price");
                done();
            });
        });
        test("Viewing the same stock and liking it again:", function (done) {
            chai
            .request(server)
            .get("/api/stock-prices/")
            .set("content-type", "application/json")
            .query({stock: "GOOG", like:true})
            .end(function(err,res){
                assert.equal(res.status, 200);
                assert.property(res.body, "stockData");
                assert.equal(res.body.stockData.stock, "GOOG");
                assert.equal(res.body.stockData.likes, 1);
                assert.exists(res.body.stockData.price, "GOOG has a price");
                done();
            });
        });
        test("Viewing two stocks:", function (done) {
            chai
            .request(server)
            .get("/api/stock-prices/")
            .set("content-type", "application/json")
            .query({stock: ["GOLD", "AMZN"], like: true})
            .end(function(err,res){
                assert.equal(res.status, 200);
                assert.property(res.body, "stockData");
                assert.equal(res.body.stockData[0].stock, "GOLD");
                assert.equal(res.body.stockData[1].stock, "AMZN");
                assert.exists(res.body.stockData[0].price, "GOLD has a price");
                assert.exists(res.body.stockData[1].price, "AMZN has a price");
                done();
            });
        });
        test("Viewing two stocks and liking them:", function (done) {
            chai
            .request(server)
            .get("/api/stock-prices/")
            .set("content-type", "application/json")
            .query({stock: ["GOLD", "AMZN"], like: true})
            .end(function(err,res){
                assert.equal(res.status, 200);
                assert.property(res.body, "stockData");
                assert.equal(res.body.stockData[0].stock, "GOLD");
                assert.equal(res.body.stockData[1].stock, "AMZN");
                assert.exists(res.body.stockData[0].price, "GOLD has a price");
                assert.exists(res.body.stockData[1].price, "AMZN has a price");
                assert.exists(res.body.stockData[0].rel_likes, "has rel_likes");
                assert.exists(res.body.stockData[1].rel_likes, "has rel_likes");
                done();
            });
        });
    })  
});

I’d appreciate any help i can get.

I don’t know what your problem is.
AFAIK, no line in .env file may have any space. DB=mongodb+…
And I believe, NODE_ENV=test should be ‘un-commented out’

1 Like

Thanks a lot for the help it improved the issue but i still need help.
Information Security project, stock price checker is what i’m working on please.

HI @faytey7 !

I haven’t worked on this project so I won’t be much help there but I would suggest putting this in a replit for now and sharing the link so other developers can play around with the code and might be able to see the issue better.

Good luck!

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.