res.status not a function when trying to set the status code

元气小坏坏 提交于 2020-01-14 10:13:10

问题


When attempting to meet the specification set by unit tests supplied, when attempting to return the status code for a method I am hit with

TypeError: res.status is not a function

when running the function createUser in the API implementation. It happens with every method call, such as res.send, res.sendStatus etc. Even if I add res.status() to the testing to set it there, it returns the same error.

apiTests.js

let chai = require('chai');
let expect = chai.expect;
let sinon = require('sinon');
let sinonChai = require('sinon-chai');
chai.use(sinonChai);

let model = require('../tron_model.js'); // for stubbing only
let api = require('../tron_api.js');

describe('API', function() {
    describe('creating users', function() {
        it('should return 201 on creating user', function () {
            let mockModel = sinon.stub(new model.TronModel());
            mockModel.addUser.onFirstCall().returns(new model.User('user','pass'));
            let req = {body: {username: 'goatzilla', password: 'x'}};
            let res = {end: function(){}};
            api.init(mockModel);
            api.createUser(req, res);
            expect(res.statusCode).to.equal(201);
            expect(mockModel.addUser).to.have.callCount(1);
        });
    });
});

tron_api.js

let model = undefined;
let api = exports;

api.init = function(modelArg) {
    model = modelArg;
};

api.createUser = function(req, res) {
    model.addUser(req.body.username, req.body.password);
    console.log(res);
    res.status(201);
};

回答1:


You mocked a res object with this code:

let res = {end: function(){}};

that does not have a .status() method and then passed that to your api.createUser() function which expects to call res.status() (a method that is not on your mocked object). A mocked object will need to have every method on it that your code calls.

In addition, you are also testing the property res.statusCode with this:

expect(res.statusCode).to.equal(201);

which also does not exist on your mocked object. While res.status() is a built-in capability in Express, res.statusCode is not a documented property (though it does appear to exist).

You could add to your mocked res object like this:

let res = {
    end: function(){}
    status: function(s) {this.statusCode = s; return this;}
};

To get it to pass those two tests.



来源:https://stackoverflow.com/questions/47502851/res-status-not-a-function-when-trying-to-set-the-status-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!