I have a controller class which instantiates a model class and I want to test that the controller uses the correct parameters when it instantiates the model. I have found that stubbing methods on a class with sinon is no problem, but if I need to stub the constructor, I can't get it to work.
This is my controller:
import settings from '../../config/settings';
import model from '../models/Form';
let content;
export default class Form {
constructor (app) {
content = new model(app.settings.content);
}
}
And this is the test (so far)
import {assert} from 'chai';
import sinon from 'sinon';
import fs from 'fs';
import settings from '../../../config/settings';
import model from '../../../lib/models/Form';
import controller from '../../../lib/controllers/Form';
let mocks;
describe('Form controller', () => {
beforeEach((done) => {
mocks = {};
mocks.model = sinon.createStubInstance(model);
done();
});
afterEach((done) => {
mocks = null;
done();
});
describe('New Forms controller', () => {
beforeEach((done) => {
mocks.app = {
settings: {
content: '/content/path/',
views: '/views/path/'
}
};
mocks.controller = new controller(mocks.app);
done();
});
it('Instantiates a model', (done) => {
assert.isTrue(mocks.model.calledWith(mocks.app.settings.content));
done();
});
});
});
I run the tests with this command:
npm run test-unit
//which equates to
"test-unit": "BABEL_DISABLE_CACHE=1 ./node_modules/.bin/mocha --recursive --check-leaks --reporter spec --bail --compilers js:babel/register ./test/unit"
The model class is built with the same pattern as the controller (e.g. export default class, constructor, etc). The problem is that in the controller constructor the model is not a stub but just the class itself.
Any suggestions on how to do this, or even whether I need to be testing this are more than welcome.
Aucun commentaire:
Enregistrer un commentaire