Search code examples
javascriptmongodbjestjssupertest

cannot get correct result from put operation via npm supertest in jest


The put operation is working fine in other models that have concrete attribute, but it fails in this model that refer to another model by mongoDB ObjectID.

Need some help in this code snippet, the output gives the original data rather than updated one. I have logged out the progress, object is indeed updated but the response from supertest module is unchanged.

This code is about the test.

  describe('PUT /:id', () => {
    it('should update a specific solution', async () => {
      const answer = await Answer.findOne({
        content: 'good answer here'
      })
      const solution = await Solution.findOne({
        answer: answer._id
      })
      const codeID = solution.code;
      const answerUP = new mongoose.Types.ObjectId().toString();
      const codeUP = new mongoose.Types.ObjectId().toString();
      const solutionUp = {
        answer: answerUP,
        code: codeUP
      };
      const res = await request(server)
        .put(`${root}/${solution._id}`)
        .send(solutionUp);

      const updated = await Solution.findById(solution._id);
      const revert = await Solution.findByIdAndUpdate(solution._id, {
        answer: answer._id,
        code: codeID
      })
      const reverted = await Solution.findById(solution._id).populate(['answer', 'code']);

      console.log('Updated:', updated);
      console.log('reverted:', reverted);

      expect(res.status).toBe(200);
      expect(res.body).toHaveProperty('answer', answerUP);
      expect(res.body).toHaveProperty('code', codeUP);
    })
  })

This is about the logging info from jest.

  ● /solutions › PUT /:id › should update a specific solution
                                                                                                                                                                                   
    expect(received).toHaveProperty(path, value)

    Expected path: "answer"

    Expected value: "62fc15ae5f22653969d4d702"
    Received value: "62fc15a51aa9ad1b58f48f4f"

       98 |
       99 |       expect(res.status).toBe(200);
    > 100 |       expect(res.body).toHaveProperty('answer', answerUP);
          |                        ^
      101 |       expect(res.body).toHaveProperty('code', codeUP);
      102 |       // expect(res.body.answer).toEqual(answerUP);
      103 |       // expect(res.body).toHaveProperty('code', codeUP);

      at Object.toHaveProperty (tests/integration/solutions.test.js:100:24)

Here is the full project from github: https://github.com/Alex-Lin5/Algorithm-Coding-Pool


Solution

  • The problem is in the routing part of solutions, I forget to add an option for mongoose model that update to the new one. I should add , {new: true}Like this:

      const solution = await Solution.findByIdAndUpdate(req.params.id, {
        answer: req.body.answer,
        code: req.body.code
      }, {new: true})