-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.test.js
More file actions
548 lines (438 loc) · 21.5 KB
/
index.test.js
File metadata and controls
548 lines (438 loc) · 21.5 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
require('expect-puppeteer');
const snapshotSerializer = require('jest-serializer-xml');
const path = require('path');
const configFiles = [
'action_conf',
'navigation_conf',
'custom_conf',
'meta_conf',
'type_conf',
'combo_conf',
'type_full_conf',
'meta_full_conf',
]
// Make tests deterministic
Date.now = jest.fn(() => 1482363367071);
jest.setTimeout(15000); // 20 second timeout for promise resolution.
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms) )
}
var useful = `
function get_by_id(doc, id) {
if (!id)
return null
if (id[0] == '#') { id = id.slice(1) }
var elem = doc.querySelector('[*|id=\\'' + id + '\\']')
if (elem) {
return elem
} else {
return Array.from(doc.getElementsByTagName('*')).find((x) => { return x.getAttribute('id') == id || x.getAttribute('xml:id') == id })
}
}
// From any relation element to list of MEI note elements
function relation_get_notes(mei,he) {
he = get_by_id(mei, get_id(he))
var note_nodes = relation_allnodes(mei, he)
var notes = note_nodes.map(node_to_note_id).map((n) => get_by_id(mei, n))
return notes
}
// From any relation element to list of MEI note elements
function relation_get_notes_separated(mei, he) {
he = get_by_id(mei, get_id(he))
var prim_nodes = relation_primaries(mei, he)
var prims = prim_nodes.map(node_to_note_id).map((n) => get_by_id(mei, n))
var sec_nodes = relation_secondaries(mei, he)
var secs = sec_nodes.map(node_to_note_id).map((n) => get_by_id(mei, n))
return [prims, secs]
}
// Get the MEI-graph nodes that are adjacent to a relation
function relation_allnodes(mei, he) {
var arcs_array = Array.from(mei.getElementsByTagName('arc'))
var nodes = []
arcs_array.forEach((a) => {
if (a.getAttribute('from') == '#' + he.getAttribute('xml:id')) {
nodes.push(get_by_id(mei, a.getAttribute('to')))
}
})
return nodes
}
function get_id(elem) {
if (document.contains(elem)) {
// SVG traversal
if (!elem.hasAttribute('oldid'))
return elem.id
else
return get_id(document.getElementById(elem.getAttribute('oldid')))
} else if (elem.hasAttribute('xml:id')) {
// MEI traversal
if (elem.hasAttribute('sameas'))
return get_id(get_by_id(window.mei, elem.getAttribute('sameas')))
else if (elem.hasAttribute('corresp'))
return get_id(get_by_id(window.mei, elem.getAttribute('corresp')))
else if (elem.hasAttribute('copyof'))
return get_id(get_by_id(window.mei, elem.getAttribute('copyof')))
else if (elem.hasAttribute('xml:id'))
return elem.getAttribute('xml:id')
}
}
function node_to_note_id(note) {
if (note.getElementsByTagName('label')[0].children.length == 0)
return note.getAttribute('xml:id')
return note.getElementsByTagName('label')[0].
getElementsByTagName('note')[0].
getAttribute('corresp').replace('#', '')
}
// Get the MEI-graph nodes that are adjacent and primary to a relation
function relation_primaries(mei_graph, he) {
var arcs_array = Array.from(mei_graph.getElementsByTagName('arc'))
var nodes = []
arcs_array.forEach((a) => {
if (a.getAttribute('from') == '#' + he.getAttribute('xml:id') &&
a.getAttribute('type') == 'primary') {
nodes.push(get_by_id(mei_graph.getRootNode(), a.getAttribute('to')))
}
})
return nodes
}
// Get the MEI-graph nodes that are adjacent and secondary to a relation
function relation_secondaries(mei_graph, he) {
var arcs_array = Array.from(mei_graph.getElementsByTagName('arc'))
var nodes = []
arcs_array.forEach((a) => {
if (a.getAttribute('from') == '#' + he.getAttribute('xml:id') &&
a.getAttribute('type') == 'secondary') {
nodes.push(get_by_id(mei_graph.getRootNode(), a.getAttribute('to')))
}
})
return nodes
}
`
const verbose = false;
let log = () => null
// Helper function to test a single button
// with a compulsory element id and any other attribute-value pairs.
var button_test = async (buttonId, conditions) => {
log(`testing button with element ID #${buttonId}`
+ (conditions ? ` and attributes ${JSON.stringify(conditions)}` : ''));
// Expect the element to exist
await expect(page)
.toMatchElement(`#${buttonId}`);
// ... to be an <input> or a <button> element
await expect(page.evaluate(`$('#${buttonId}').prop('tagName').toLowerCase()`)).resolves
.toMatch(/input|button/); // is an <input> element
// ... of type `button`
await expect(page.evaluate(`$('#${buttonId}').attr('type')`)).resolves
.toMatch('button');
// ... fulfilling any {attr, value} pairwise conditions
if (conditions) {
for (const c in conditions) {
await expect(page.evaluate(`$('#${buttonId}').attr('${c}')`)).resolves
.toMatch(conditions[c]);
}
}
}
describe('reductive_analysis_test_suite', () => {
beforeAll(async () => {
await page.goto("http://localhost:8000");
// Make tests deterministic
await wait(1000)
await page.evaluate('Date.now = () => 1482363367071')
await page.evaluate(useful)
if (verbose) {
log = console.log
}
log("DOM fully loaded and parsed?");
});
it('should run a rudimentary test on static HTML to confirm Jest works', async function () {
await expect(page.title()).resolves.toMatch(/^DCML/s, { timeout: 30000 });
//await expect(page).toMatch(/Primaries.*Secondaries/s, {timeout: 30000});
});
/* it('should parse conf.js without throwing an exception', function () {
configFiles.forEach(async filename => {
await expect(page.evaluate(filename)).resolves.toBeTruthy();
})
});*/
it('should load the example MEI', async function() {
await expect(page).toUploadFile(
'input[type=file]',
path.join(__dirname, 'test_scores', 'mozart13.xml')
);
await expect(page).toMatchElement('div.layer');
});
it('should set up all buttons with expected element IDs and attributes', async function () {
// Wrapping in `await expect` seems to be needed to make `window` available.
await expect(async () => {
// Test programmatically generated relation buttons.
Object.keys(window.type_conf).forEach(async (b) =>
await button_test(`${b}relationbutton`, { 'class': 'relationbutton' })
);
// Test programmatically generated metarelation buttons.
Object.keys(window.meta_conf).forEach(async (b) =>
await button_test(`${b}metarelationbutton`, { 'class': 'metarelationbutton' })
);
// Test hard-wired buttons.
await button_test('undobutton');
await button_test('deselectbutton');
await button_test('deletebutton');
await button_test('relationbutton', { 'class': 'relationbutton' });
await button_test('player-play');
await button_test('player-pause');
await button_test('player-stop');
await button_test('downloadbutton');
await button_test('svgdownloadbutton');
await button_test('equalizebutton');
await button_test('shadesbutton');
})
});
it('should have loaded view-specific buttons', async function () {
await expect(async () => {
button_test('reducebutton', {'class': 'reducebutton'});
button_test('unreducebutton', {'class': 'unreducebutton'});
button_test('rerenderbutton', {'class': 'rerenderbutton'});
button_test('newlayerbutton', {'class': 'newlayerbutton'});
button_test('zoominbutton', {'class': 'zoominbutton'});
button_test('zoomoutbutton', {'class': 'zoomoutbutton'});
})
});
it('should produce a directed <graph> within <mei>', async function () {
await page.waitForTimeout(3300);
await expect(page.evaluate(`window.mei.querySelector('graph').getAttribute('type')`)).resolves
.toMatch(/^directed$/);
});
it(`should produce a convincing <mei> object (using Jest snapshots)`, async function() {
expect.addSnapshotSerializer(snapshotSerializer);
var mei_to_str = await page.evaluate(`window.mei.children[0].outerHTML`);
// Prevent false positives by stripping out conversion timestamps (in case of XML->MEI).
mei_to_str = mei_to_str.replace(/isodate="\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d"/gm, '');
// Prevent false positives by stripping out converter-generated random IDs (in case of XML->MEI).
mei_to_str = mei_to_str.replace(/xml:id="\w+-\d+"/gm, '');
expect(mei_to_str).toMatchSnapshot();
});
it('should produce a convincing SVG (using Jest snapshots)', async function() {
expect.addSnapshotSerializer(snapshotSerializer);
var svg_to_str = await
page.evaluate(`window.document.querySelector('div.svg_container').children[0].outerHTML`);
// Prevent false positives by stripping out Verovio-generated random attributes.
svg_to_str = svg_to_str.replace(/id="\w+-\d+"/gm, '');
svg_to_str = svg_to_str.replace(/section-\d+/gm, '');
expect(svg_to_str).toMatchSnapshot();
});
it('should ensure that (the very last) note IDs of the MEI and the SVG match', async function () {
// There is probably a better way to test this.
var mei_id = await page.evaluate(`window.mei.querySelector('note').getAttribute('xml:id')`);
var svg_id = await page.evaluate(`window.document.querySelector('g.note').getAttribute('id')`);
expect(mei_id).toMatch(svg_id);
})
it('should toggle a note, ensuring that the relevant array is updated and the note styled accordingly', async function () {
log(`About to toggle a note`);
var svg_first_note_id = await page.evaluate(`window.document.querySelector('g.note').getAttribute('id')`);
var svg_first_note_selector = `#${svg_first_note_id}`;
var svg_first_notehead_selector = `#${svg_first_note_id} .notehead`;
// Simulate click on the first note.
log('Selecting note.')
await expect(page).toClick(svg_first_notehead_selector);
// Confirm that the selected note has been styled accordingly.
// (I *think* that Jest-Puppeteer does not provide async monitoring of global state,
// so checking for DOM changes before global state seems generally prudent. This might be worth revisiting.)
await expect(page).toMatchElement(svg_first_note_selector + `[class*="selectednote"]`);
log(await page.evaluate('selected[0]'))
// Confirm that the selected note has been added to the `selected` array.
await expect(page.evaluate(`window.selected[0].getAttribute('id')`)).resolves.toEqual(svg_first_note_id)
// The relations menu covers the notes we want to poke at, so we should
// move it down
const drag_box_x = await page.evaluate('document.querySelector(`.fly-out__drag`).getBoundingClientRect().x')
const drag_box_width = await page.evaluate('document.querySelector(`.fly-out__drag`).getBoundingClientRect().width')
const drag_box_y = await page.evaluate('document.querySelector(`.fly-out__drag`).getBoundingClientRect().y')
const drag_box_height = await page.evaluate('document.querySelector(`.fly-out__drag`).getBoundingClientRect().height')
await page.mouse.move(drag_box_x + drag_box_width / 2, drag_box_y + drag_box_height /2 )
await page.mouse.down()
await page.mouse.move(drag_box_x + drag_box_width / 2, drag_box_y + drag_box_height /2 + 300)
await page.mouse.up()
// Simulate second click on first note (deselecting it).
log('Deselecting note.')
await expect(page).toClick(svg_first_notehead_selector);
// Confirm that the selected note has been styled accordingly.
await expect(page).toMatchElement(svg_first_note_selector + `:not([class*="selectednote"])`);
// Confirm that the selected note has been added to the `selected` array.
await expect(page.evaluate(`window.selected[0]`)).resolves.toBeFalsy();
});
it('should extra-toggle a note, ensuring that the relevant array is updated and the note styled accordingly', async function () {
log(`About to extra-toggle a note`);
var svg_first_note_id = await page.evaluate(`window.document.querySelector('g.note').getAttribute('id')`);
var svg_first_note_selector = `#${svg_first_note_id}`;
var svg_first_notehead_selector = `#${svg_first_note_id} .notehead`;
// Simulate click on the first note.
log('Selecting note.')
await page.keyboard.down('Shift');
await expect(page).toClick(svg_first_notehead_selector);
await page.keyboard.up('Shift');
// Confirm that the selected note has been styled accordingly.
// (I *think* that Jest-Puppeteer does not provide async monitoring of global state,
// so checking for DOM changes before global state seems generally prudent. This might be worth revisiting.)
await expect(page).toMatchElement(svg_first_note_selector + `[class*="extraselectednote"]`);
// Confirm that the selected note has been added to the `selected` array.
await expect(page.evaluate(`window.extraselected[0].getAttribute('id')`)).resolves.toEqual(svg_first_note_id);
// Simulate second click on first note (deselecting it).
log('Deselecting note.')
await page.keyboard.down('Shift');
await expect(page).toClick(svg_first_notehead_selector);
await page.keyboard.up('Shift');
// Confirm that the selected note has been styled accordingly.
await expect(page).toMatchElement(svg_first_note_selector + `:not([class*="extraselectednote"])`);
// Confirm that the selected note has been added to the `selected` array.
await expect(page.evaluate(`window.extraselected[0]`)).resolves.toBeFalsy();
});
it('should toggle a new relation between structurally unequal notes', async function () {
// Pick the first two notes for this test.
var primary_id = await page.evaluate(`window.document.querySelectorAll('g.note')[0].id`);
var secondary_id = await page.evaluate(`window.document.querySelectorAll('g.note')[1].id`);
log(`About to create relationship between primary #${primary_id} and secondary #${secondary_id}.`);
// Simulate click on the first note.
await page.keyboard.down('Shift');
await expect(page).toClick(`#${primary_id} .notehead`);
await page.keyboard.up('Shift');
log('Selected primary note.')
// Simulate click on the secondary note.
await expect(page).toClick(`#${secondary_id} .notehead`);
log('Selected secondary note.')
// Enter arpeggio relation via the keyboard shortcut.
await page.keyboard.press('a');
log('Created test relation.')
// // Assert MEI nodes with respective xml:id attributes.
// // TODO: Understand why the following saner and faster alternative doesn't seem to work.
// // Note: wrapping in await `expect(async => ())` seems to work. No idea why.
// await expect(async () => {
// await expect(page.evaluate(`window.mei.querySelector('node[*|id*="${primary_id}"]')`)).resolves
// .toBeTruthy();
// await expect(page.evaluate(`window.mei.querySelector('node[*|id*="${secondary_id}"]')`)).resolves
// .toBeTruthy();
// })
await expect(page
.evaluate(`
Object.entries(window.mei.querySelectorAll('node'))
.map ( x => x[1].outerHTML
.match(/xml:id="gn-${primary_id}"/) ? true : false )`))
.resolves
.toIncludeAllMembers([true]);
await expect(page
.evaluate(`
Object.entries(window.mei.querySelectorAll('node'))
.map ( x => x[1].outerHTML
.match(/xml:id="gn-${secondary_id}"/) ? true : false )`))
.resolves
.toIncludeAllMembers([true]);
// Assert relation <arc>'s for primary and secondary notes.
// TODO: This should likely be revisited for compliance with the TEI-derived standard.
// See https://github.com/DCMLab/reductive_analysis_app/issues/48.
var expected_relation_id = await page.evaluate(`window.mei
.querySelector('arc[to="#gn-${primary_id}"][type="primary"]')
.getAttribute('from')
.substring(1)`); // remove the hash prefix from the ID, for consistency.
log(`Expecting to match the primary-node arc with relation id: #${expected_relation_id}.`);
await expect(page.evaluate(`window.mei
.querySelector('arc[to="#gn-${secondary_id}"][type="secondary"][from="#${expected_relation_id}"]')`)).resolves
.toBeTruthy();
log(`Found a matching secondary-node arc with the expected relation id: #${expected_relation_id}.`);
// Assert that a node of type `relation` has been added to the MEI tree.
await expect(page.evaluate(`
window.test_relation = Object.entries(window.mei.querySelectorAll('node[type="relation"]'))
.filter( x => x[1]
.outerHTML
.match(/xml:id="${expected_relation_id}"/) )[0][1]`
))
.resolves
.toBeTruthy();
// Assert a graphic element for the relation.
await expect(page).toMatchElement(`path#${expected_relation_id}`);
// Assert that notes are retrievable from the test relation (`relation_get_notes`).
await expect(page.evaluate(`
window.test_notes = relation_get_notes(window.mei,
window.test_relation
).map(n => n.getAttribute('xml:id'))
`)).resolves.toBeTruthy();
var notes_to_test = await page.evaluate(`window.test_notes`);
log(`Note id's returned by relation_get_notes: #${notes_to_test[0]} #${notes_to_test[1]}`);
log(`Primary and secondary note id's to be matched by those of relation_get_notes: #${primary_id} #${secondary_id}`);
// Assert that the notes retrieved from the relation are valid.
expect([primary_id, secondary_id]).toIncludeAllMembers(notes_to_test);
// Assert that primary and secondary notes are retrievable from relations (`relation_get_notes_separated`).
await expect(page.evaluate(`
window.test_notes_separated = relation_get_notes_separated(window.mei,
window.test_relation
).map(n => n[0].getAttribute('xml:id'))
`)).resolves.toBeTruthy();
var notes_to_test_separated = await page.evaluate(`window.test_notes_separated`);
log(`Note id's returned by relation_get_notes_separated: #${notes_to_test_separated[0]} #${notes_to_test_separated[1]}`);
log(`Primary and secondary note id's to be matched by those of relation_get_notes: #${primary_id} #${secondary_id}`);
// Assert that the notes retrieved from the relation are valid.
expect([primary_id, secondary_id]).toEqual(notes_to_test_separated);
// Attempt to press Undo.
await page.keyboard.press('U');
log('Pressed Undo via keyboard shortcut.')
// Confirm that the relation is no longer drawn.
await expect(page.evaluate(`window.test_relation`)).resolves.toEqual({});
// Confirm that the relation node is removed from the graph.
await expect(page.evaluate(`
document.querySelectorAll('path[id="${expected_relation_id}"]')[0]
`)).resolves.toBeNil();
// Confirm that the relevant note nodes are removed from the graph.
await expect(page.evaluate(`
// Checking for any residual nodes is enough because the only possibly remaining
// (relation) node has already been ruled out.
window.mei.querySelector('node');
`)).resolves.toBeNull();
// Confirm that the relevant arcs are removed from the graph.
await expect(page.evaluate(`
window.mei.querySelector('arc');
`)).resolves.toBeNull();
});
it('should reduce the relation between structurally unequal notes, hiding the less important one', async function () {
// Re-enter arpeggio relation via the keyboard shortcut.
await page.keyboard.press('a');
log('Re-created test relation.')
// Find and click the reduce button
// First we need to get the reducebutton to be shown
await page.keyboard.press('-');
var buttons_id = "layers-menu-toggle";
await expect(page).toClick(`#${buttons_id}`);
await wait(1000)
var reducebutton_id = "layers-menu-reduce";
await expect(page).toClick(`#${reducebutton_id}`);
log('Reduced the test relation.');
// Check that the secondary note has been hidden
var secondary_id = await page.evaluate(`window.document.querySelectorAll('g.note')[1].id`);
await expect(page.evaluate(`
document.querySelectorAll('g[id="${secondary_id}"]')[0].classList.contains("hidden") `
)).resolves.toBeTruthy();
// And also the relation
var expected_relation_id = await page.evaluate(`window.mei
.querySelector('arc[to="#gn-${secondary_id}"][type="secondary"]')
.getAttribute('from')
.substring(1)`); // remove the hash prefix from the ID, for consistency.
await expect(page.evaluate(`
document.querySelectorAll('path[id="${expected_relation_id}"]')[0].classList.contains("hidden") `
)).resolves.toBeTruthy();
});
it('should unreduce the relation, showing it again', async function () {
// Find and click the unreducebutton
var unreducebutton_id = "layers-menu-unreduce";
await expect(page).toClick(`#${unreducebutton_id}`);
log('Unreduced the test relation.');
// Check that the secondary note is shown again
var secondary_id = await page.evaluate(`window.document.querySelectorAll('g.note')[1].id`);
await expect(page.evaluate(`
document.querySelectorAll('g[id="${secondary_id}"]')[0].classList.contains("hidden") `
)).resolves.toBeFalsy();
// And also the relation
var expected_relation_id = await page.evaluate(`window.mei
.querySelector('arc[to="#gn-${secondary_id}"][type="secondary"]')
.getAttribute('from')
.substring(1)`); // remove the hash prefix from the ID, for consistency.
await expect(page.evaluate(`
document.querySelectorAll('path[id="${expected_relation_id}"]')[0].classList.contains("hidden") `
)).resolves.toBeFalsy();
var reducebutton_id = "layers-menu-reduce";
await expect(page).toClick(`#${reducebutton_id}`);
log('Re-reduced the test relation.');
});
});