Repository navigation
Expand file tree
/
Copy pathcode.component.spec.ts
More file actions
289 lines (245 loc) · 10.2 KB
/
Copy pathcode.component.spec.ts
File metadata and controls
289 lines (245 loc) · 10.2 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
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Component, DebugElement } from '@angular/core';
import { MdSnackBarModule, MdSnackBar } from '@angular/material';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { CodeComponent } from './code.component';
import { CopierService } from 'app/shared//copier.service';
import { Logger } from 'app/shared/logger.service';
import { PrettyPrinter } from './pretty-printer.service';
const oneLineCode = 'const foo = "bar";';
const smallMultiLineCode = `
<hero-details>
<h2>Bah Dah Bing</h2>
<hero-team>
<h3>NYC Team</h3>
</hero-team>
</hero-details>`;
const bigMultiLineCode = smallMultiLineCode + smallMultiLineCode + smallMultiLineCode;
describe('CodeComponent', () => {
let codeComponentDe: DebugElement;
let codeComponent: CodeComponent;
let hostComponent: HostComponent;
let fixture: ComponentFixture<HostComponent>;
// WARNING: Chance of cross-test pollution
// CodeComponent injects PrettyPrintService
// Once PrettyPrintService runs once _anywhere_, its ctor loads `prettify.js`
// which sets `window['prettyPrintOne']`
// That global survives these tests unless
// we take strict measures to wipe it out in the `afterAll`
// and make sure THAT runs after the tests by making component creation async
afterAll(() => {
delete window['prettyPrint'];
delete window['prettyPrintOne'];
});
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ MdSnackBarModule, NoopAnimationsModule ],
declarations: [ CodeComponent, HostComponent ],
providers: [
PrettyPrinter,
CopierService,
{provide: Logger, useClass: TestLogger }
]
});
});
// Must be async because
// CodeComponent creates PrettyPrintService which async loads `prettify.js`.
// If not async, `afterAll` finishes before tests do!
beforeEach(async(() => {
fixture = TestBed.createComponent(HostComponent);
hostComponent = fixture.componentInstance;
codeComponentDe = fixture.debugElement.children[0];
codeComponent = codeComponentDe.componentInstance;
fixture.detectChanges();
}));
it('should create CodeComponent', () => {
expect(codeComponentDe.name).toBe('aio-code', 'selector');
expect(codeComponent).toBeTruthy('CodeComponent');
});
describe('pretty printing', () => {
it('should format a one-line code sample', () => {
// 'pln' spans are a tell-tale for syntax highlighing
const spans = codeComponentDe.nativeElement.querySelectorAll('span.pln');
expect(spans.length).toBeGreaterThan(0, 'formatted spans');
});
function hasLineNumbers() {
// presence of `<li>`s are a tell-tale for line numbers
return 0 < codeComponentDe.nativeElement.querySelectorAll('li').length;
}
it('should format a one-line code sample without linenums by default', () => {
expect(hasLineNumbers()).toBe(false);
});
it('should add line numbers to one-line code sample when linenums set true', () => {
hostComponent.linenums = 'true';
fixture.detectChanges();
expect(hasLineNumbers()).toBe(true);
});
it('should format a small multi-line code without linenums by default', () => {
hostComponent.code = smallMultiLineCode;
fixture.detectChanges();
expect(hasLineNumbers()).toBe(false);
});
it('should add line numbers to a big multi-line code by default', () => {
hostComponent.code = bigMultiLineCode;
fixture.detectChanges();
expect(hasLineNumbers()).toBe(true);
});
it('should format big multi-line code without linenums when linenums set false', () => {
hostComponent.linenums = false;
hostComponent.code = bigMultiLineCode;
fixture.detectChanges();
expect(hasLineNumbers()).toBe(false);
});
});
describe('whitespace handling', () => {
it('should remove common indentation from the code before rendering', () => {
hostComponent.linenums = false;
hostComponent.code = ' abc\n let x = text.split(\'\\n\');\n ghi\n\n jkl\n';
fixture.detectChanges();
const codeContent = codeComponentDe.nativeElement.querySelector('code').textContent;
expect(codeContent).toEqual('abc\n let x = text.split(\'\\n\');\nghi\n\njkl');
});
it('should trim whitespace from the code before rendering', () => {
hostComponent.linenums = false;
hostComponent.code = '\n\n\n' + smallMultiLineCode + '\n\n\n';
fixture.detectChanges();
const codeContent = codeComponentDe.nativeElement.querySelector('code').textContent;
expect(codeContent).toEqual(codeContent.trim());
});
it('should trim whitespace from code before computing whether to format linenums', () => {
hostComponent.code = '\n\n\n' + hostComponent.code + '\n\n\n';
fixture.detectChanges();
// `<li>`s are a tell-tale for line numbers
const lis = codeComponentDe.nativeElement.querySelectorAll('li');
expect(lis.length).toBe(0, 'should be no linenums');
});
});
describe('error message', () => {
function getErrorMessage() {
const missing: HTMLElement = codeComponentDe.nativeElement.querySelector('.code-missing');
return missing ? missing.textContent : null;
}
it('should not display "code-missing" class when there is some code', () => {
fixture.detectChanges();
expect(getErrorMessage()).toBeNull('should not have element with "code-missing" class');
});
it('should display error message when there is no code (after trimming)', () => {
hostComponent.code = ' \n ';
fixture.detectChanges();
expect(getErrorMessage()).toContain('missing');
});
it('should show path and region in missing-code error message', () => {
hostComponent.code = ' \n ';
hostComponent.path = 'fizz/buzz/foo.html';
hostComponent.region = 'something';
fixture.detectChanges();
expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html#something$/);
});
it('should show path only in missing-code error message when no region', () => {
hostComponent.code = ' \n ';
hostComponent.path = 'fizz/buzz/foo.html';
fixture.detectChanges();
expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html$/);
});
it('should show simple missing-code error message when no path/region', () => {
hostComponent.code = ' \n ';
fixture.detectChanges();
expect(getErrorMessage()).toMatch(/missing.$/);
});
});
describe('copy button', () => {
function getButton() {
const btnDe = fixture.debugElement.query(By.css('button'));
return btnDe ? btnDe.nativeElement : null;
}
it('should be hidden if the `hideCopy` input is true', () => {
hostComponent.hideCopy = true;
fixture.detectChanges();
expect(getButton()).toBe(null);
});
it('should have title', () => {
fixture.detectChanges();
expect(getButton().title).toBe('Copy code snippet');
});
it('should have no aria-label by default', () => {
fixture.detectChanges();
expect(getButton().getAttribute('aria-label')).toBe('');
});
it('should have aria-label explaining what is being copied when title passed in', () => {
hostComponent.title = 'a/b/c/foo.ts';
fixture.detectChanges();
expect(getButton().getAttribute('aria-label')).toContain(hostComponent.title);
});
it('should call copier service when clicked', () => {
const copierService: CopierService = TestBed.get(CopierService);
const spy = spyOn(copierService, 'copyText');
expect(spy.calls.count()).toBe(0, 'before click');
getButton().click();
expect(spy.calls.count()).toBe(1, 'after click');
});
it('should copy code text when clicked', () => {
const copierService: CopierService = TestBed.get(CopierService);
const spy = spyOn(copierService, 'copyText');
getButton().click();
expect(spy.calls.argsFor(0)[0]).toBe(oneLineCode, 'after click');
});
it('should preserve newlines in the copied code', () => {
const copierService: CopierService = TestBed.get(CopierService);
const spy = spyOn(copierService, 'copyText');
const expectedCode = smallMultiLineCode.trim().replace(/</g, '<').replace(/>/g, '>');
let actualCode;
hostComponent.code = smallMultiLineCode;
[false, true, 42].forEach(linenums => {
hostComponent.linenums = linenums;
fixture.detectChanges();
codeComponent.ngOnChanges();
getButton().click();
actualCode = spy.calls.mostRecent().args[0];
expect(actualCode).toBe(expectedCode, `when linenums=${linenums}`);
expect(actualCode.match(/\r?\n/g).length).toBe(5);
spy.calls.reset();
});
});
it('should display a message when copy succeeds', () => {
const snackBar: MdSnackBar = TestBed.get(MdSnackBar);
const copierService: CopierService = TestBed.get(CopierService);
spyOn(snackBar, 'open');
spyOn(copierService, 'copyText').and.returnValue(true);
getButton().click();
expect(snackBar.open).toHaveBeenCalledWith('Code Copied', '', { duration: 800 });
});
it('should display an error when copy fails', () => {
const snackBar: MdSnackBar = TestBed.get(MdSnackBar);
const copierService: CopierService = TestBed.get(CopierService);
spyOn(snackBar, 'open');
spyOn(copierService, 'copyText').and.returnValue(false);
getButton().click();
expect(snackBar.open).toHaveBeenCalledWith('Copy failed. Please try again!', '', { duration: 800 });
});
});
});
//// Test helpers ////
// tslint:disable:member-ordering
@Component({
selector: 'aio-host-comp',
template: `
<aio-code md-no-ink [code]="code" [language]="language"
[linenums]="linenums" [path]="path" [region]="region"
[hideCopy]="hideCopy" [title]="title"></aio-code>
`
})
class HostComponent {
code = oneLineCode;
hideCopy: boolean;
language: string;
linenums: boolean | number | string;
path: string;
region: string;
title: string;
}
class TestLogger {
log = jasmine.createSpy('log');
error = jasmine.createSpy('error');
}