问题
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