-
Notifications
You must be signed in to change notification settings - Fork 61
/
hooks.js
93 lines (75 loc) · 2.35 KB
/
hooks.js
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
const hooks = require('hooks');
const {MongoClient} = require('mongodb');
let client;
let db;
// Fixtures
const gist = {
'_id': '42',
'created_at': new Date().toISOString(),
'description': 'Gist description...',
'content': 'String content...',
}
const star = {
'gist_id': '42',
'starred': true,
}
// Setup database connection before Dredd starts testing
hooks.beforeAll((transactions, done) => {
const mongoURI = process.env.MONGO_URI || 'mongodb://localhost';
MongoClient.connect(mongoURI, { useNewUrlParser: true }, function (err, c) {
if (!err) {
client = c;
db = c.db('dredd-example');
}
done(err);
});
});
// Close database connection after Dredd finishes testing
hooks.afterAll((transactions, done) => {
client.close();
done();
});
// Before each test let's fix the media type - unfortunately current support
// of OpenAPI2 in Dredd works only for application/json as of now
hooks.beforeEach((transaction, done) => {
let contentType;
if (transaction.expected.statusCode == '204') {
transaction.request.headers['Accept'] = 'text/plain';
delete transaction.expected.headers['Content-Type'];
} else {
transaction.request.headers['Accept'] = 'application/hal+json';
transaction.expected.headers['Content-Type'] = 'application/hal+json';
}
done();
});
// After each test clear contents of the database (we want isolated tests)
hooks.afterEach((transaction, done) => {
db.collection('gists').deleteMany({}, (err) => {
if (err) { return done(err) }
db.collection('stars').deleteMany({}, (err) => {
done(err);
});
});
});
// To test work with Gists and Stars in isolation, we need to add some prior
// to certain HTTP transactions Dredd is about to make
hooks.before('/gists/{id} > GET > 200 > application/json', (transaction, done) => {
db.collection('gists').insertOne(gist, (err) => {
done(err);
});
});
hooks.before('/gists/{id} > PATCH > 200 > application/json', (transaction, done) => {
db.collection('gists').insertOne(gist, (err) => {
done(err);
});
});
hooks.before('/gists > GET > 200 > application/json', (transaction, done) => {
db.collection('gists').insertOne(gist, (err) => {
done(err);
});
});
hooks.before('/gists/{id}/star > GET > 200 > application/json', (transaction, done) => {
db.collection('stars').insertOne(star, (err) => {
done(err);
});
});