2

Is there a way to assert the value of a property on res.locals? For example consider:

        res.locals.authenticated = false;
        res.render('index');

Now to test this:

        expect(res.status).to.equal(200);
        expect(res.locals.authenticated).to.be.false

I get a type error Cannot read property 'authenticated' of undefined

How can I test a property I pass to res.locals?

Here is the full code:

router.get('/', function (req, res) {

        res.locals.authenticated = false;
        res.render('index');

});

And I'm testing with Mocha, chai, and chai-http:

it('should respond with contents of the homepage', function (done) {

    chai.request(server).get('/').end(function (err, res) {
        expect(err).to.be.null;
        expect(res.status).to.equal(200);
        expect(res.locals.authenticated).to.be.false;
        expect(res).to.be.html;
        done();
    });
});
JohnSnow
  • 6,911
  • 8
  • 23
  • 44
  • 1
    I see no reason why you should't be able. But it seems that in your case `res.locals` is not defined. Can you share the flow? – Yoni Levy Feb 22 '17 at 14:54
  • @YoniLevy I added the entire snippet above. Keep in mind that everything works, I just want my tests to pass. – JohnSnow Feb 22 '17 at 15:01
  • 1
    Looking at the docs (http://expressjs.com/en/api.html#res.locals) it seems that `res.locals` is only visible to the view(s) rendered, So testing it in `end` probably won't get you far. You may need to hack your way into the rendering engine but it seems like a poor solution. – Yoni Levy Feb 22 '17 at 15:29
  • So is there any way to test the properties of res.locals then ? – JohnSnow Feb 22 '17 at 15:31
  • Not that I know of but then again I didn't really dig in to it. – Yoni Levy Feb 22 '17 at 15:33
  • See if you indeed get `res.locals` in your view – Yoni Levy Feb 22 '17 at 15:33
  • rec.locals is not accessible where you need it. See https://stackoverflow.com/a/26811414/387094 for a pretty good explanation of why. – Travis Stevens Oct 23 '19 at 21:59

0 Answers0