upsert.test.js
3.19 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'use strict';
var chai = require('chai')
, sinon = require('sinon')
, Sequelize = require('../../../index')
, Promise = Sequelize.Promise
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../../lib/data-types')
, dialect = Support.getTestDialect()
, datetime = require('chai-datetime')
, _ = require('lodash')
, assert = require('assert')
, current = Support.sequelize;
chai.use(datetime);
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser('Model'), function() {
beforeEach(function() {
this.User = this.sequelize.define('user', {
username: DataTypes.STRING,
foo: {
unique: 'foobar',
type: DataTypes.STRING
},
bar: {
unique: 'foobar',
type: DataTypes.INTEGER
}
});
return this.sequelize.sync({ force: true });
});
if (current.dialect.supports.upserts) {
describe('upsert', function() {
it('works with upsert on id', function() {
return this.User.upsert({ id: 42, username: 'john' }).bind(this).then(function(created) {
if (dialect === 'sqlite') {
expect(created).not.to.be.defined;
} else {
expect(created).to.be.ok;
}
return this.sequelize.Promise.delay(1000).bind(this).then(function() {
return this.User.upsert({ id: 42, username: 'doe' });
});
}).then(function(created) {
if (dialect === 'sqlite') {
expect(created).not.to.be.defined;
} else {
expect(created).not.to.be.ok;
}
return this.User.find(42);
}).then(function(user) {
expect(user.createdAt).to.be.defined;
expect(user.username).to.equal('doe');
expect(user.updatedAt).to.be.afterTime(user.createdAt);
});
});
it('works with upsert on a composite key', function() {
return this.User.upsert({ foo: 'baz', bar: 19, username: 'john' }).bind(this).then(function(created) {
if (dialect === 'sqlite') {
expect(created).not.to.be.defined;
} else {
expect(created).to.be.ok;
}
return this.sequelize.Promise.delay(1000).bind(this).then(function() {
return this.User.upsert({ foo: 'baz', bar: 19, username: 'doe' });
});
}).then(function(created) {
if (dialect === 'sqlite') {
expect(created).not.to.be.defined;
} else {
expect(created).not.to.be.ok;
}
return this.User.find({ where: { foo: 'baz', bar: 19 }});
}).then(function(user) {
expect(user.createdAt).to.be.defined;
expect(user.username).to.equal('doe');
expect(user.updatedAt).to.be.afterTime(user.createdAt);
});
});
it('supports validations', function () {
var User = this.sequelize.define('user', {
email: {
type: Sequelize.STRING,
validate: {
isEmail: true
}
}
});
return expect(User.upsert({ email: 'notanemail' })).to.eventually.be.rejectedWith(this.sequelize.ValidationError);
});
});
}
});