samedi 20 mars 2021

How do I add data in sql database with Sequelize when testing in Node

I'm trying to test if data can be added to the database such as a login account. I first setup the Sequelize connection and try to add to data to it through sync() however it returns me an error with Access denied for user ''@'localhost' (using password: NO).

auth-controller.js

const expect = require('chai').expect;
const sinon = require('sinon');
const { Sequelize } = require('sequelize');

const User = require('../models/user');
const AuthController = require('../controllers/auth');

describe('Auth Controller', function () {
  before(async function (done) {
    let sequelize = new Sequelize('my_database', 'root', 'password', {
      dialect: 'mysql',
      host: 'localhost',
      port: 3306
    });
    let test;

    try {
      test = await sequelize.authenticate()
      console.log('Successfully connected to database!');
    } catch (e) {
      console.log('Connection to the database failed!: ' + e.message);
      throw e;
    }
})

Returns Successfully connected to database!

In the methods below I attempt to add data to the database

Method 1:

describe('Auth Controller', function () {
  before(async function (done) {
    let sequelize = new Sequelize('my_database', 'root', 'password', {
      dialect: 'mysql',
      host: 'localhost',
      port: 3306
    });
    let test;

    try {
      test = await sequelize.authenticate().then(result => {
        const user = new User({
          id: 1,
          email: 'test@test.com',
          password: 'tester',
          name: 'Test'
        });
        return user.save();
      });
      console.log('Successfully connected to database!');
    } catch (e) {
      console.log('Connection to the database failed!: ' + e.message);
      throw e;
    }
  

Error: Connection to the database failed!: Access denied for user ''@'localhost' (using password: NO)

Method 2:

describe('Auth Controller', function () {
  before(async function (done) {
    let sequelize = new Sequelize('my_database', 'root', 'password', {
      dialect: 'mysql',
      host: 'localhost',
      port: 3306
    });
    let test;

    try {
      test = await sequelize.authenticate().then(result => {
        const user = new User({
          id: 1,
          email: 'test@test.com',
          password: 'tester',
          name: 'Test'
        });
        return user.save();
      });
      console.log('Successfully connected to database!');
    } catch (e) {
      console.log('Connection to the database failed!: ' + e.message);
      throw e;
    }
})

Error: AccessDeniedError [SequelizeAccessDeniedError]: Access denied for user ''@'localhost' (using password: NO) I'm doing a very similar thing to method 2 in my app.js which works however in this test it fails to add.

How can I resolve this issue?

Aucun commentaire:

Enregistrer un commentaire