Exercise tracker Tests broken?

I’ve tested all the requirements manually, and apparently, they are OK, but when I run the tests, cant pass these:

-The response returned from POST /api/users/:_id/exercises will be the user object with the exercise fields added.

  • The date property of any object in the log array that is returned from GET /api/users/:id/logs should be a string… Use the dateString format of the Date API.

  • You can add from , to and limit parameters to a GET /api/users/:_id/logs request to retrieve part of the log of any user. from and to are dates in yyyy-mm-dd format. limit is an integer of how many logs to send back.

the expected output is the same as in the freeCodeCamp solution, but even so, it doesn’t work… also, when I tested the solution from freeCodeCamp, even they have related issues…

my Code is:

//connect to mongodb
mongoose.connect(process.env['MONGO_URI'], { useNewUrlParser: true, useUnifiedTopology: true });

//basic config
app.use(cors())
app.use(express.static('public'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});
app.use(bodyParser.urlencoded({extended: false}))

// create the schema and the model
const userSchema = new Schema({
  username:{ type: String, required: true },
  log:[{
    description:{ type: String, required: true },
    duration:{ type: Number, required: true },
    date: { type: Date, required: true }
  }]
})

const User = mongoose.model("user",userSchema)

//create new user
app.post('/api/users',(req,res)=>{
  
  let username = req.body.username

  var user  = new User({
    username: `${username}`,  
  })
  user.save(function(err,data){
    if (err) return console.error(err);
    //console.log(data)
    res.send({
    "username":username,
    "_id":data._id
  }) 
  })
  
})

//show new user
app.get('/api/users',(req,res)=>{
  User.find({},function(err,users){
    var userMap = [];

    users.forEach(function(user) {    
      userMap.push({
        "_id":user.id,
        "username": user.username
      })     
    });
    res.send(userMap);  
  })
})

/// create an excercise
app.post("/api/users/:_id/exercises",(req,res,next)=>{
  let userId = req.params._id
  let description = req.body.description
  let duration = req.body.duration
  let date = req.body.date
  
  if (date === "" || "undefined"){
    date = new Date().toDateString()
  } else {
    date = new Date(date).toDateString()
  } 

  const expObj = {
    description,
    duration,
    date
  }

  User.findByIdAndUpdate(
    userId,
    {$push:{log:expObj}},
    {new:true},
    (err,updatedUser)=>{
      if(err) {
        return console.log('update error:',err);
      }
      
      let returnObj ={
        "_id":userId,
        "username":updatedUser.username,
        "date":expObj.date,
        "duration":parseInt(expObj.duration),"description":expObj.description
      }
      res.json(returnObj)
    }
  )  
})


//retrieve info of exercises
app.get('/api/users/:_id/logs',(req,res)=>{
  const userId = req.params._id
  const from = req.query.from;
  const to = req.query.to;
  const limit = +req.query.limit;

  User.findById({_id:userId},(err,user)=>{
    if(err) return console.log(err)     

    let log = user.log.map((item)=>{
      return {
        description:item.description,
        duration:item.duration,
        date: new Date(item.date).toDateString()
      }     
    })
    if (from){
      const fromDate = new Date(from)
      log = log.filter(exe => new Date(exe.date)>= fromDate)
    }
    if (to){
      const toDate = new Date(to)
      log = log.filter(exe => new Date(exe.date)<= toDate)
    }
    if(limit){
      log = log.slice(0,limit)
    }

    let count = log.length  
 
    res.send({      
      "username":user.username,
      "count":count,
      "_id":userId,
      "log":log
    })
  })  
})

const listener = app.listen(process.env.PORT || 3000, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})

My project link

https://boilerplate-project-exercisetracker.nicolascaldero9.repl.co

My browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36

Challenge: Exercise Tracker

Link to the challenge:

1 Like

It’s the code and not the tests, sorry. I modified your offending POST route thusly:

app.post("/api/users/:_id/exercises",(req,res,next)=>{
  console.log(req.body);
  console.log(req.params);
  console.log(req.query);
  let userId = req.params._id
  let description = req.body.description
  let duration = req.body.duration
  let date = req.body.date
  
  console.log(date);

  if (date === "" || "undefined"){
    date = new Date().toDateString()
  } else {
    date = new Date(date).toDateString()
  }

  console.log(date);

  const expObj = {
    description,
    duration,
    date
  }

  User.findByIdAndUpdate(
    userId,
    {$push:{log:expObj}},
    {new:true},
    (err,updatedUser)=>{
      if(err) {
        console.log('update error:',err);
        return res.json('update error:', err);
      }
      
      let returnObj ={
        "_id":userId,
        "username":updatedUser.username,
        "date":expObj.date,
        "duration":parseInt(expObj.duration),"description":expObj.description
      }
      console.log(returnObj)
      return res.json(returnObj)
    }
  )  
})

and got the following output for a test:

[Object: null prototype] {
  description: 'test',
  duration: '60',
  date: '1990-01-02'
}
{ _id: '6172159bea7ece0e65f13089' }
{}
1990-01-02
Fri Oct 22 2021
{
  _id: '6172159bea7ece0e65f13089',
  username: 'fcc_test_16348665872',
  date: 'Fri Oct 22 2021',
  duration: 60,
  description: 'test'
}

which shows that the date is getting mangled. The cause is

because that second part of the or is always true since it is a non-empty string and not the identifier undefined.

Since you are storing incorrect dates, I would assume that this is why the other test is failing as it would be returning incorrect dates. Regardless, you can track the problem as I have by logging all the route inputs, logging all the route responses, and returning all the route responses in the problematic routes.

Thanks Jeremy!
I was a fool handling dates, but you were right, so I changed my approach to handling “undefined”:

let date = req.body.date?new Date(req.body.date).toDateString() : new Date().toDateString()

but I still have this error:

  • The date property of any object in the log array that is returned from GET /api/users/:id/logs should be a string… Use the dateString format of the Date API.

I console.log all dates from the tests… and apparently, all are “strings”, so I still don’t understand what’s wrong :frowning:

(postscript: I wrote that about " test broken", not because of my code, but because if you test de official link of the application provided by freeCodeCamp: “https://exercise-tracker.freecodecamp.rocks/”, the same error appears )

1 Like

without any other changes to the code… when I submitted it today passed the remaining tests, thanks for your help

I’m still experiencing the same issue where the test
The dateproperty of any object in thelogarray that is returned fromGET /api/users/:id/logsshould be a string.. Use thedateStringformat of theDate API.
does not pass despite the data being correct. The tests output is:

{"username":"fcc_test_16474427368","_id":"1647442736919","log":[{"description":"test","duration":60,"date":"Thu Jan 01 1970"}],"count":1}
{"username":"fcc_test_16474427373","_id":"1647442737418","log":[{"description":"test","duration":60,"date":"Thu Jan 01 1970"}],"count":1}
{"username":"fcc_test_16474427378","_id":"1647442737952","log":[{"description":"test","duration":60,"date":"Thu Jan 01 1970"}],"count":1}
{"username":"fcc_test_16474427384","_id":"1647442738518","log":[{"description":"test","duration":60,"date":"Thu Jan 01 1970"}],"count":1}
{"username":"fcc_test_16474427389","_id":"1647442739012","log":[{"description":"test","duration":60,"date":"Thu Jan 01 1970"}],"count":1}
{"username":"fcc_test_16474427393","_id":"1647442739509","log":[{"description":"test","duration":60,"date":"Thu Jan 01 1970"}],"count":1}
{"username":"fcc_test_16474427398","_id":"1647442740001","log":[{"description":"test","duration":60,"date":"Thu Jan 01 1970"}],"count":1}
{"username":"fcc_test_16474427404","_id":"1647442740508","log":[{"description":"test","duration":60,"date":"Mon Jan 01 1990"},{"description":"test","duration":60,"date":"Wed Jan 03 1990"}],"count":2}
{"username":"fcc_test_16474427404","_id":"1647442740508","log":[{"description":"test","duration":60,"date":"Mon Jan 01 1990"}],"count":1}
{"username":"fcc_test_16474427404","_id":"1647442740508","log":[{"description":"test","duration":60,"date":"Mon Jan 01 1990"}],"count":1}

@robcarbon Please open a new thread for your question and provide the link to the code.