Reputation: 835
I want to mock a method of ES6 class.
I am importing models module:
// test.js
const models = require(path.resolve('./models'));
In models folder there is an index.js and it redirects to index.js in user folder while calling models.user:
// models/index.js
models.user = user;
Then I have a user class in index.js: // models/user/index.js
class User extends Model {
// simplified exists - it returns boolean or thows an error
static async exists(username) {
if (username) {
returns true
} else {
throw new Error('bad output');
}
}
}
I want to stub exist(username) method with sinon stub.
I am doing:
const sinon = require('sinon');
const models = require(path.resolve('./models'));
describe.only('generateTokenBehavior()', function() {
it('should return 200 given valid username and password', function() {
...
const stub = sinon.stub();
stub(models.user.prototype, 'exists').callsFake(true);
...
});
and I am getting an error on the line with stub:
TypeError: Cannot read property 'callsFake' of undefined
What is wrong with this code? I was researching this problem on similar stack questions but didn't find the answer.
Upvotes: 1
Views: 11885
Reputation: 950
The problem here is that calling the result of sinon.stub() as a function returns undefined.
const sinon = require('sinon');
const models = require(path.resolve('./models'));
describe.only('generateTokenBehavior()', function() {
it('should return 200 given valid username and password', function() {
...
const stub = sinon.stub(models.user.prototype, 'exists').callsFake(true);
...
});
For reference, the documentation is here: http://sinonjs.org/releases/v4.1.1/stubs/#properties
I don't blame you for writing it the way you did - the documentation is a bit misleading.
Upvotes: 2