'How to unit test a method in a sequelize model file?
I need to create some unit tests for a method in my auth.model file. I was able to get some simple assertions done with sequelize-test-helpers, however I'm not sure how to call/test the method Auth.updateForgotPassword. I was told that I need to setup a mock connection to the DB so I can then use the method within the file. Refactoring the code is not an option at the moment. This is a node.js app using sequelize to map to a Postgres database.
auth.model.js
'use strict';
const Sequelize = require('sequelize');
const { forgotPassword } = require('../util/forgotPasswordCognitoHelper');
const { getErrorResponse } = require('../util/errorStatusHelper');
module.exports = (sequelize, DataTypes) => {
const Auth = sequelize.define(
'Auth',
{
userId: {
type: DataTypes.INTEGER,
primaryKey: true,
field: 'user_id',
},
principalId: {
type: DataTypes.TEXT,
field: 'principal_id',
},
},
{
tableName: 'user_auth',
timestamps: false,
paranoid: false,
version: false,
sequelize,
}
);
Auth.associate = function (models) {
models.Auth.belongsTo(models.User, {
foreignKey: 'userId',
sourceKey: 'userId',
});
};
Auth.updateForgotPassword = async function (args = {}) {
const Models = require('./index');
const response = {
status: 'NOT_FOUND',
};
try {
const auth = await Models.Auth.findOne({
where: { principalId: args.username },
});
if (auth) {
await forgotPassword(
args.username,
args.password,
args.confirmationCode
);
response.status = 'SUCCESS';
}
} catch (ex) {
response.status = getErrorResponse(ex);
console.log(ex);
}
return response;
};
return Auth;
};
auth.test.js
const { expect } = require('chai')
const { match, stub, resetHistory } = require('sinon')
const proxyquire = require('proxyquire')
const {
sequelize,
dataTypes,
checkModelName,
checkPropertyExists,
} = require('sequelize-test-helpers')
describe('Auth Model Test Suite', function () {
const AuthModel = require('../../../models/auth.model')
const Auth = AuthModel(sequelize, dataTypes)
let auth
this.beforeAll(function () {
auth = new Auth()
})
describe('Model name', function () {
checkModelName(Auth)('Auth')
})
describe('Model properties', function () {
auth = new Auth();
['userId',
'principalId'
].forEach(checkPropertyExists(auth));
})
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
