0

I am learning to use Chai and Mocha to create unit tests. Right now I am having a heck of a time figuring out how to access the req object. I have seen in multiple places in the documentation that you can use expect(req) in multiple ways, but it never says how to access req. When I try to I am greeted with

"Uncaught ReferenceError: req is not defined".

For example in the below code, I can get expect(res) statements to work. Now I would like to test that the id property has been added properly to the req object by my middleware.

I have tried everything and simply cannot figure this out. Thanks in advance!

//Imports necessary modules
const chai = require('chai');
const chaiHttp = require('chai-http');
const expect = chai.expect;
const {mockData} = require('./mock-data.js')
const app = require('../app.js');

chai.use(chaiHttp);

describe('/process POST', () => {
    it('it should calculate the points value and add it to the req object', (done) => {
        chai.request(app).post('/').send(mockData).end((err, res) => {
            expect(req).to.have.property('id')
            done();
        });
    });
}

Edit: I have tried accessing res.req as I have seen elsewhere which didn't work for me. I've tried including it in the callback used for end (err, req, res) => {} which also didn't work. I also tried accessing it in a .then() but also it didn't work. I see req being used in the official documentation, but I have no idea how to access it.

Brenden
  • 60
  • 7
  • 1
    Where does the `req` variable defined in your code? – Lin Du Jun 28 '23 at 01:12
  • @Lin As normal in a router I have middlware functions such as (req, res, next) => {some code}. I am able to access the res object also in chai, but not the req. Thanks! – Brenden Jun 28 '23 at 02:50

0 Answers0