BlinkUX / sequelize-mock

A simple mock interface specifically for testing code relying on Sequelize models
https://sequelize-mock.readthedocs.io
MIT License
139 stars 73 forks source link

findOne() saving over table variable #69

Open Amber-Williams opened 5 years ago

Amber-Williams commented 5 years ago

Using the following code and I think there's an issue with the findOne() method because it saves over my table variable in my testing with Jest. const SequelizeMock = require('sequelize-mock'); let dbMock = new SequelizeMock(); let UserMock = dbMock.define('test', { test: 'test', name: 'no' }

describe('Sequelize Model Testing',() => { test('testingggg', async () => { let user = await UserMock.findOne({ where: { name: 'amber' } }) expect(user.name).toBe('amber'); }) })

The expect user.name should be 'no' but its returning as 'amber'.

bublig737 commented 5 years ago

I have the same problem!

stoked10 commented 4 years ago

Same problem, the findOne seems to be creating the record if it doesn't exist and returns it, my code:

workerController

const { worker } = require('../../models');

async function getAll() {
  const aws = await worker.findAll();

  return aws;
}

async function getOne(id) {
  const aw = await worker.findById(id);

  return aw.get({ plain: true });
}

module.exports = {
  getAll,
  getOne,
};

spec

const Worker = require('../../app/controllers/workerController');
const { worker } = require('../../models');

jest.mock('../../models/worker', () => () => {
  // eslint-disable-next-line global-require
  const SequelizeMock = require('sequelize-mock');
  const dbMock = new SequelizeMock();
  return dbMock.define('worker', {
    id: '6037c891-8237-4596-9665-645b2b6a1f4a',
    available: true,
    createdAt: new Date(),
    updatedAt: new Date(),
  });
});

describe('Worker Controller Functions', () => {
  fit('test', async () => {
    const all = await Worker.getAll();
    console.log(`BEFORE GET_ONE: ${JSON.stringify(all, null, 2)}`);
    const result = await Worker.getOne('1');
    console.log(`RESULT: ${JSON.stringify(result, null, 2)}`);
    expect(result.id).toEqual('1');
  });
});

Results in the following output:

    BEFORE GET_ONE: [
      {
        "id": "6037c891-8237-4596-9665-645b2b6a1f4a",
        "available": true,
        "createdAt": "2019-09-25T11:30:36.629Z",
        "updatedAt": "2019-09-25T11:30:36.629Z"
      }
    ]

    RESULT: {
      "id": "1",
      "available": true,
      "createdAt": "2019-09-25T11:30:36.629Z",
      "updatedAt": "2019-09-25T11:30:36.629Z"
    }

Test Suites: 1 passed, 1 total
stoked10 commented 4 years ago

Never mind, found this in the code base for findById:

/**