jbrumwell / mock-knex

A mock knex adapter for simulating a database during testing
MIT License
240 stars 71 forks source link

How to configure the inserted record ID? #67

Closed gajus closed 7 years ago

gajus commented 7 years ago

I cannot figure out how to set the inserted record ID.

const dataSourceModel = new DataSourceModel({name: 'foo'});

await dataSourceModel.save(null, {
  method: 'insert',
  require: true,
  transacting: transaction
});

Here is what I have tried:

test('inserts record to the database', async (t) => {
  const userId = 1;
  const newRecordId = 2;

  const runner = createRunner([
    (query) => {
      t.true(query.sql === 'BEGIN;');

      query.response([]);
    },
    (query) => {
      t.true(query.sql === 'insert into `data_source` (`name`) values (?)');
      t.deepEqual(query.bindings, ['foo']);

+      query.response(newRecordId);
    },
    (query) => {
      t.true(query.sql === 'insert into `data_source_history` (`action_name`, `data_source_id`, `data_source_name`, `revision_number`, `user_id`) values (?, DEFAULT, ?, ?, ?)');
      t.deepEqual(query.bindings, ['insert', 'foo', 0, userId]);

      query.response([]);
    },
    (query) => {
      t.true(query.sql === 'COMMIT;');

      query.response([]);
    }
  ]);

  tracker.on('query', runner);

  await createDataSource({}, {
    name: 'foo'
  }, {
    authorization: {
      some: () => {}
    },
    userId
  });
});

But this way id remains undefined.

jbrumwell commented 7 years ago

The response should be [<id>] for inserts I believe not ato a pc to confirm though

gajus commented 7 years ago

You are right. Should have thought of that.

Thank you.

jbrumwell commented 7 years ago

No problem glad it worked :-)

pragmaticivan commented 4 years ago

Lost some minutes here on that one, it deserves to be in the docs, thanks! The fact that the README only shows select queries kinda threw me off a bit.