optimistic_locking.test.js
2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'use strict';
const Support = require('../support');
const DataTypes = require('../../../lib/data-types');
const chai = require('chai');
const expect = chai.expect;
describe(Support.getTestDialectTeaser('Model'), () => {
describe('optimistic locking', () => {
let Account;
beforeEach(async function() {
Account = this.sequelize.define('Account', {
number: {
type: DataTypes.INTEGER
}
}, {
version: true
});
await Account.sync({ force: true });
});
it('should increment the version on save', async () => {
const account0 = await Account.create({ number: 1 });
account0.number += 1;
expect(account0.version).to.eq(0);
const account = await account0.save();
expect(account.version).to.eq(1);
});
it('should increment the version on update', async () => {
const account1 = await Account.create({ number: 1 });
expect(account1.version).to.eq(0);
const account0 = await account1.update({ number: 2 });
expect(account0.version).to.eq(1);
account0.number += 1;
const account = await account0.save();
expect(account.number).to.eq(3);
expect(account.version).to.eq(2);
});
it('prevents stale instances from being saved', async () => {
await expect((async () => {
const accountA = await Account.create({ number: 1 });
const accountB0 = await Account.findByPk(accountA.id);
accountA.number += 1;
await accountA.save();
const accountB = await accountB0;
accountB.number += 1;
return await accountB.save();
})()).to.eventually.be.rejectedWith(Support.Sequelize.OptimisticLockError);
});
it('increment() also increments the version', async () => {
const account1 = await Account.create({ number: 1 });
expect(account1.version).to.eq(0);
const account0 = await account1.increment('number', { by: 1 } );
const account = await account0.reload();
expect(account.version).to.eq(1);
});
it('decrement() also increments the version', async () => {
const account1 = await Account.create({ number: 1 });
expect(account1.version).to.eq(0);
const account0 = await account1.decrement('number', { by: 1 } );
const account = await account0.reload();
expect(account.version).to.eq(1);
});
});
});