/
qunit-helpers.js
464 lines (405 loc) · 12.2 KB
/
qunit-helpers.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
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
import QUnit, { module } from "qunit";
import MessageBus from "message-bus-client";
import {
clearCache as clearOutletCache,
resetExtraClasses,
} from "discourse/lib/plugin-connectors";
import { clearRewrites, setURLContainer } from "discourse/lib/url";
import {
currentSettings,
mergeSettings,
} from "discourse/tests/helpers/site-settings";
import { forceMobile, resetMobile } from "discourse/lib/mobile";
import { getApplication, getContext } from "@ember/test-helpers";
import { getOwner, setDefaultOwner } from "discourse-common/lib/get-owner";
import { later, run } from "@ember/runloop";
import { moduleFor, setupApplicationTest } from "ember-qunit";
import HeaderComponent from "discourse/components/site-header";
import { Promise } from "rsvp";
import Site from "discourse/models/site";
import User from "discourse/models/user";
import { _clearSnapshots } from "select-kit/components/composer-actions";
import { clearHTMLCache } from "discourse/helpers/custom-html";
import createStore from "discourse/tests/helpers/create-store";
import deprecated from "discourse-common/lib/deprecated";
import { flushMap } from "discourse/models/store";
import { initSearchData } from "discourse/widgets/search-menu";
import { isEmpty } from "@ember/utils";
import { mapRoutes } from "discourse/mapping-router";
import { resetCustomPostMessageCallbacks } from "discourse/controllers/topic";
import { resetDecorators } from "discourse/widgets/widget";
import { resetCache as resetOneboxCache } from "pretty-text/oneboxer";
import { resetDecorators as resetPluginOutletDecorators } from "discourse/components/plugin-connector";
import { resetDecorators as resetPostCookedDecorators } from "discourse/widgets/post-cooked";
import { resetTopicTitleDecorators } from "discourse/components/topic-title";
import { resetUsernameDecorators } from "discourse/helpers/decorate-username-selector";
import { resetWidgetCleanCallbacks } from "discourse/components/mount-widget";
import { resetUserSearchCache } from "discourse/lib/user-search";
import sessionFixtures from "discourse/tests/fixtures/session-fixtures";
import { setTopicList } from "discourse/lib/topic-list-tracker";
import sinon from "sinon";
import siteFixtures from "discourse/tests/fixtures/site-fixtures";
import { clearResolverOptions } from "discourse-common/resolver";
import { clearNavItems } from "discourse/models/nav-item";
import {
cleanUpComposerUploadHandler,
cleanUpComposerUploadMarkdownResolver,
cleanUpComposerUploadProcessor,
} from "discourse/components/composer-editor";
const LEGACY_ENV = !setupApplicationTest;
export function currentUser() {
return User.create(sessionFixtures["/session/current.json"].current_user);
}
export function updateCurrentUser(properties) {
run(() => {
User.current().setProperties(properties);
});
}
// Note: do not use this in acceptance tests. Use `loggedIn: true` instead
export function logIn() {
User.resetCurrent(currentUser());
}
// Note: Only use if `loggedIn: true` has been used in an acceptance test
export function loggedInUser() {
return User.current();
}
export function fakeTime(timeString, timezone = null, advanceTime = false) {
let now = moment.tz(timeString, timezone);
return sinon.useFakeTimers({
now: now.valueOf(),
shouldAdvanceTime: advanceTime,
});
}
export function withFrozenTime(timeString, timezone, callback) {
const clock = fakeTime(timeString, timezone, false);
try {
callback();
} finally {
clock.restore();
}
}
let _pretenderCallbacks = {};
export function resetSite(siteSettings, extras) {
let siteAttrs = $.extend({}, siteFixtures["site.json"].site, extras || {});
siteAttrs.store = createStore();
siteAttrs.siteSettings = siteSettings;
return Site.resetCurrent(Site.create(siteAttrs));
}
export function applyPretender(name, server, helper) {
const cb = _pretenderCallbacks[name];
if (cb) {
cb(server, helper);
}
}
export function controllerModule(name, args = {}) {
moduleFor(name, name, {
setup() {
this.registry.register("router:main", mapRoutes());
let controller = this.subject();
controller.siteSettings = currentSettings();
if (args.setupController) {
args.setupController(controller);
}
},
needs: args.needs,
});
}
export function discourseModule(name, options) {
// deprecated(
// `${name}: \`discourseModule\` is deprecated. Use QUnit's \`module\` instead.`,
// { since: "2.6.0" }
// );
if (typeof options === "function") {
module(name, function (hooks) {
hooks.beforeEach(function () {
this.container = getOwner(this);
this.registry = this.container.registry;
this.owner = this.container;
this.siteSettings = currentSettings();
clearResolverOptions();
});
this.getController = function (controllerName, properties) {
let controller = this.container.lookup(`controller:${controllerName}`);
if (!LEGACY_ENV) {
controller.application = {};
}
controller.siteSettings = this.siteSettings;
if (properties) {
controller.setProperties(properties);
}
return controller;
};
this.moduleName = name;
options.call(this, hooks);
});
return;
}
module(name, {
beforeEach() {
this.container = getOwner(this);
this.siteSettings = currentSettings();
if (options && options.beforeEach) {
options.beforeEach.call(this);
}
},
afterEach() {
if (options && options.afterEach) {
options.afterEach.call(this);
}
},
});
}
export function addPretenderCallback(name, fn) {
if (name && fn) {
if (_pretenderCallbacks[name]) {
// eslint-disable-next-line no-console
throw `There is already a pretender callback with module name (${name}).`;
}
_pretenderCallbacks[name] = fn;
}
}
export function acceptance(name, optionsOrCallback) {
name = `Acceptance: ${name}`;
let callback;
let options = {};
if (typeof optionsOrCallback === "function") {
callback = optionsOrCallback;
} else if (typeof optionsOrCallback === "object") {
deprecated(
`${name}: The second parameter to \`acceptance\` should be a function that encloses your tests.`,
{ since: "2.6.0" }
);
options = optionsOrCallback;
}
addPretenderCallback(name, options.pretend);
let loggedIn = false;
let mobileView = false;
let siteChanges;
let settingChanges;
let userChanges;
const setup = {
beforeEach() {
resetMobile();
// For now don't do scrolling stuff in Test Mode
HeaderComponent.reopen({ examineDockHeader: function () {} });
resetExtraClasses();
if (mobileView) {
forceMobile();
}
if (loggedIn) {
logIn();
if (userChanges) {
updateCurrentUser(userChanges);
}
}
if (settingChanges) {
mergeSettings(settingChanges);
}
this.siteSettings = currentSettings();
clearOutletCache();
clearHTMLCache();
resetSite(currentSettings(), siteChanges);
if (LEGACY_ENV) {
getApplication().__registeredObjects__ = false;
getApplication().reset();
}
this.container = getOwner(this);
if (LEGACY_ENV && loggedIn) {
updateCurrentUser({
appEvents: this.container.lookup("service:app-events"),
});
}
setURLContainer(this.container);
setDefaultOwner(this.container);
if (!this.owner) {
this.owner = this.container;
}
if (options.beforeEach) {
options.beforeEach.call(this);
}
},
afterEach() {
let app = getApplication();
if (options && options.afterEach) {
options.afterEach.call(this);
}
flushMap();
localStorage.clear();
User.resetCurrent();
resetExtraClasses();
clearOutletCache();
clearHTMLCache();
clearRewrites();
initSearchData();
resetDecorators();
resetPostCookedDecorators();
resetPluginOutletDecorators();
resetTopicTitleDecorators();
resetUsernameDecorators();
resetOneboxCache();
resetCustomPostMessageCallbacks();
resetUserSearchCache();
clearNavItems();
setTopicList(null);
_clearSnapshots();
setURLContainer(null);
setDefaultOwner(null);
cleanUpComposerUploadHandler();
cleanUpComposerUploadProcessor();
cleanUpComposerUploadMarkdownResolver();
app._runInitializer("instanceInitializers", (initName, initializer) => {
if (initializer && initializer.teardown) {
initializer.teardown(this.container);
}
});
if (LEGACY_ENV) {
app.__registeredObjects__ = false;
app.reset();
}
// We do this after reset so that the willClearRender will have already fired
resetWidgetCleanCallbacks();
},
};
const needs = {
user(changes) {
loggedIn = true;
userChanges = changes;
},
pretender(fn) {
addPretenderCallback(name, fn);
},
site(changes) {
siteChanges = changes;
},
settings(changes) {
settingChanges = changes;
},
mobileView() {
mobileView = true;
},
};
if (options.loggedIn) {
needs.user();
}
if (options.site) {
needs.site(options.site);
}
if (options.settings) {
needs.settings(options.settings);
}
if (options.mobileView) {
needs.mobileView();
}
if (callback) {
// New, preferred way
module(name, function (hooks) {
needs.hooks = hooks;
hooks.beforeEach(setup.beforeEach);
hooks.afterEach(setup.afterEach);
callback(needs);
if (!LEGACY_ENV && getContext) {
setupApplicationTest(hooks);
hooks.beforeEach(function () {
// This hack seems necessary to allow `DiscourseURL` to use the testing router
let ctx = getContext();
this.container.registry.unregister("router:main");
this.container.registry.register("router:main", ctx.owner.router, {
instantiate: false,
});
});
}
});
} else {
// Old way
module(name, setup);
}
}
export function controllerFor(controller, model) {
controller = getOwner(this).lookup("controller:" + controller);
if (model) {
controller.set("model", model);
}
return controller;
}
export function fixture(selector) {
if (selector) {
return $("#qunit-fixture").find(selector);
}
return $("#qunit-fixture");
}
QUnit.assert.not = function (actual, message) {
this.pushResult({
result: !actual,
actual,
expected: !actual,
message,
});
};
QUnit.assert.blank = function (actual, message) {
this.pushResult({
result: isEmpty(actual),
actual,
message,
});
};
QUnit.assert.present = function (actual, message) {
this.pushResult({
result: !isEmpty(actual),
actual,
message,
});
};
QUnit.assert.containsInstance = function (collection, klass, message) {
const result = klass.detectInstance(collection[0]);
this.pushResult({
result,
message,
});
};
export function waitFor(assert, callback, timeout) {
timeout = timeout || 500;
const done = assert.async();
later(() => {
callback();
done();
}, timeout);
}
export async function selectDate(selector, date) {
return new Promise((resolve) => {
const elem = document.querySelector(selector);
elem.value = date;
const evt = new Event("input", { bubbles: true, cancelable: false });
elem.dispatchEvent(evt);
elem.blur();
resolve();
});
}
export function queryAll(selector, context) {
context = context || "#ember-testing";
return $(selector, context);
}
export function query() {
return document.querySelector("#ember-testing").querySelector(...arguments);
}
export function invisible(selector) {
const $items = queryAll(selector + ":visible");
return (
$items.length === 0 ||
$items.css("opacity") !== "1" ||
$items.css("visibility") === "hidden"
);
}
export function visible(selector) {
return queryAll(selector + ":visible").length > 0;
}
export function count(selector) {
return queryAll(selector).length;
}
export function exists(selector) {
return count(selector) > 0;
}
export function publishToMessageBus(channelPath, ...args) {
MessageBus.callbacks
.filterBy("channel", channelPath)
.map((c) => c.func(...args));
}