Skip to content

A platform for community discussion. Free, open, simple.

DEV: Clean up QUnit setup (#45507)

Jarek Radoszac005c0e57a1
diff --git a/app/assets/stylesheets/qunit-custom.scss b/app/assets/stylesheets/qunit-custom.scss
index fe89485d0c9..48329e29471 100644
--- a/app/assets/stylesheets/qunit-custom.scss
+++ b/app/assets/stylesheets/qunit-custom.scss
@@ -53,7 +53,6 @@ body {
}
#qunit-filter-input,
- #qunit-urlconfig-qunit_single_plugin,
#qunit-urlconfig-target {
background-color: var(--secondary);
border: 1px solid var(--primary-medium);
diff --git a/app/controllers/qunit_controller.rb b/app/controllers/qunit_controller.rb
index 8c7c13145ee..151beb444a8 100644
--- a/app/controllers/qunit_controller.rb
+++ b/app/controllers/qunit_controller.rb
@@ -28,6 +28,9 @@ class QunitController < ApplicationController
target = params[:target] || "core"
+ # The toolbar's target dropdown offers theme tests too
+ return redirect_to path("/theme-qunit") if target == "theme-qunit"
+
@required_plugins = []
@testing_plugins = []
diff --git a/bin/qunit b/bin/qunit
index 56e7205de02..385ab4dbd03 100755
--- a/bin/qunit
+++ b/bin/qunit
@@ -122,6 +122,8 @@ class QunitRunner
@report_requests = true
end
+ opts.on("--report-memory", "Report JS heap usage after the tests") { @report_memory = true }
+
opts.on("--[no-]headless", "Run tests in headless mode (env: QUNIT_HEADLESS)") do |h|
@headless = h
end
@@ -282,7 +284,6 @@ class QunitRunner
env = {}
env["LOAD_PLUGINS"] = should_load_plugins? ? "1" : "0"
- env["REPORT_REQUESTS"] = "1" if @report_requests
env["UNICORN_PORT"] = @rails_port.to_s
env["TESTEM_DEFAULT_BROWSER"] = ENV["TESTEM_DEFAULT_BROWSER"] || detect_browser
env["PLUGIN_TARGETS"] = @plugin_targets.join(",") if @plugin_targets.any?
@@ -588,6 +589,7 @@ class QunitRunner
params["theme_id"] = @theme_id if @theme_id
params["target"] = resolved_target if resolved_target && !@plugin_targets.any?
params["report_requests"] = "1" if @report_requests
+ params["report_memory"] = "1" if @report_memory
params["testem"] = "1"
encode_query_string(params)
diff --git a/docs/developer-guides/docs/03-code-internals/05-run-test-suites.md b/docs/developer-guides/docs/03-code-internals/05-run-test-suites.md
index e5ce2c1973f..7c16d1c3faf 100644
--- a/docs/developer-guides/docs/03-code-internals/05-run-test-suites.md
+++ b/docs/developer-guides/docs/03-code-internals/05-run-test-suites.md
@@ -12,7 +12,7 @@ Discourse has extensive frontend tests for core, plugins and themes. Once you ha
**Themes:** Visit `/theme-qunit` in your development (or production) environment, then choose the theme
-In general, when working on core tests you should enable "Skip Plugins", and when you're working on plugins you should choose the specific plugin from the dropdown list (which will automatically 'Skip Core'). The core test suite is not expected to pass when plugins are enabled (because plugins often deliberately change core's behavior)
+In general, when working on core tests you should choose "core" from the "Target" dropdown, and when you're working on plugins you should choose the specific plugin.
> :information_source: Unfortunately, at the time of writing, memory leaks in our tests mean that trying to running the entire suite in one browser tends to hit the browser memory limit. To run the entire suite across multiple browsers in parallel, check out the CLI examples below.
diff --git a/docs/developer-guides/docs/04-plugins/06-acceptance-tests.md b/docs/developer-guides/docs/04-plugins/06-acceptance-tests.md
index dff692cde63..a1fb57065f5 100644
--- a/docs/developer-guides/docs/04-plugins/06-acceptance-tests.md
+++ b/docs/developer-guides/docs/04-plugins/06-acceptance-tests.md
@@ -76,14 +76,16 @@ After we simulate a click on the button, we can check whether the tentacle appea
assert.ok(exists(".tentacle"), "the tentacle wants to rule the world!");
```
-Not too bad is it? You can try the test yourself by visiting `http://localhost:3000/tests?qunit_single_plugin=purple-tentacle&qunit_skip_core=1` on your development machine. You should very quickly see the purple tentacle appear and all tests will pass.
+Not too bad is it? You can try the test yourself by visiting `http://localhost:3000/tests?target=purple-tentacle` on your development machine. You should very quickly see the purple tentacle appear and all tests will pass.
-If you want to run the plugin qunit tests on the command line using PhantomJS, you can run
+If you want to run the plugin qunit tests on the command line, you can run
```
-rake plugin:qunit['purple-tentacle']
+bin/qunit --target purple-tentacle
```
+(add `--standalone` if your development server isn't running)
+
(where `purple-tentacle` is the folder name of your plugin)
### Debugging your tests
diff --git a/frontend/discourse/tests/helpers/component-test.js b/frontend/discourse/tests/helpers/component-test.js
index 985c64ce7cd..5c50059963a 100644
--- a/frontend/discourse/tests/helpers/component-test.js
+++ b/frontend/discourse/tests/helpers/component-test.js
@@ -32,7 +32,7 @@ export function setupRenderingTest(hooks, opts = {}) {
hooks.beforeEach(function () {
this.siteSettings = currentSettings();
- this.registry ||= this.owner.__registry__;
+ this.registry = this.owner.__registry__;
this.container = this.owner;
this.site = Site.current();
@@ -70,6 +70,5 @@ export function setupRenderingTest(hooks, opts = {}) {
}
autoLoadModules(this.owner, this.registry);
- this.owner.lookup("service:store");
});
}
diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.js
index a21ede6ef00..df049d3f357 100644
--- a/frontend/discourse/tests/helpers/qunit-helpers.js
+++ b/frontend/discourse/tests/helpers/qunit-helpers.js
@@ -3,7 +3,6 @@ import { run } from "@ember/runloop";
import {
find,
findAll,
- getApplication,
settled,
triggerKeyEvent,
typeIn,
@@ -208,9 +207,6 @@ export function applyPretender(name, server, helper) {
// Add clean up code here to run after every test
export function testCleanup(app) {
if (_initialized.has(QUnit.config.current.testId)) {
- if (!app) {
- app = getApplication();
- }
app._runInitializer("instanceInitializers", (_, initializer) => {
initializer.teardown?.();
});
@@ -318,7 +314,7 @@ function cleanupCssGeneratorTags() {
document.querySelector("style#hashtag-css-generator")?.remove();
}
-export function addPretenderCallback(name, fn) {
+function addPretenderCallback(name, fn) {
if (name && fn) {
if (_pretenderCallbacks[name]) {
throw `There is already a pretender callback with module name (${name}).`;
@@ -331,21 +327,37 @@ export function addPretenderCallback(name, fn) {
export function acceptance(name, callback) {
name = `Acceptance: ${name}`;
- let options = {};
-
- addPretenderCallback(name, options.pretend);
-
let loggedIn = false;
let mobileView = false;
let siteChanges;
let settingChanges;
let userChanges;
- const setup = {
- beforeEach() {
+ const needs = {
+ user(changes) {
+ loggedIn = true;
+ userChanges = changes;
+ },
+ pretender(fn) {
+ addPretenderCallback(name, fn);
+ },
+ site(changes) {
+ siteChanges = changes;
+ },
+ settings(changes) {
+ settingChanges = changes;
+ },
+ mobileView() {
+ mobileView = true;
+ },
+ };
+
+ module(name, function (hooks) {
+ needs.hooks = hooks;
+
+ hooks.beforeEach(function () {
I18n.testing = true;
- resetExtraClasses();
if (mobileView) {
forceMobile();
}
@@ -369,70 +381,21 @@ export function acceptance(name, callback) {
this.container = getOwnerWithFallback(this);
- if (!this.owner) {
- this.owner = this.container;
- }
-
- if (options.beforeEach) {
- options.beforeEach.call(this);
- }
- },
+ // Hooks added via `needs.hooks` run before ember-qunit sets the owner
+ this.owner ??= this.container;
+ });
- afterEach() {
+ hooks.afterEach(function () {
I18n.testing = false;
- options?.afterEach?.call(this);
if (loggedIn) {
User.current().statusManager.stopTrackingStatus();
}
- },
- };
-
- 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);
+ callback(needs);
- setupApplicationTest(hooks);
- });
- } else {
- // Old way
- module(name, setup);
- }
+ setupApplicationTest(hooks);
+ });
}
export function fixture(selector) {
@@ -575,31 +538,19 @@ export async function selectText(selector, endOffset = null) {
range.setEnd(node, endOffset);
}
- const performSelection = () => {
- const selection = window.getSelection();
- selection.removeAllRanges();
- selection.addRange(range);
- };
-
- performSelection();
+ const selection = window.getSelection();
+ selection.removeAllRanges();
+ selection.addRange(range);
await settled();
}
-export function conditionalTest(name, condition, testCase) {
- if (condition) {
+export function chromeTest(name, testCase) {
+ if (navigator.userAgent.includes("Chrome")) {
test(name, testCase);
}
}
-export function chromeTest(name, testCase) {
- conditionalTest(name, navigator.userAgent.includes("Chrome"), testCase);
-}
-
-export function firefoxTest(name, testCase) {
- conditionalTest(name, navigator.userAgent.includes("Firefox"), testCase);
-}
-
export function silenceConsoleErrorsMatching(substring) {
const stub = sinon.stub(console, "error").callsFake((...args) => {
if (typeof args[0] === "string" && args[0].includes(substring)) {
@@ -666,13 +617,4 @@ export async function simulateKeys(element, keys) {
}
}
-// The order of attributes can vary in different browsers. When comparing
-// HTML strings from the DOM, this function helps to normalize them to make
-// comparison work cross-browser
-export function normalizeHtml(html) {
- const resultElement = document.createElement("template");
- resultElement.innerHTML = html;
- return resultElement.innerHTML;
-}
-
export const metaModifier = { [`${PLATFORM_KEY_MODIFIER}Key`]: true };
diff --git a/frontend/discourse/tests/setup-tests.js b/frontend/discourse/tests/setup-tests.js
index afaaf9b7ef2..ddf6d93ffc7 100644
--- a/frontend/discourse/tests/setup-tests.js
+++ b/frontend/discourse/tests/setup-tests.js
@@ -50,7 +50,10 @@ import {
testsTornDown,
} from "discourse/tests/helpers/qunit-helpers";
import { configureRaiseOnDeprecation } from "discourse/tests/helpers/raise-on-deprecation";
-import { resetSettings } from "discourse/tests/helpers/site-settings";
+import {
+ currentSettings,
+ resetSettings,
+} from "discourse/tests/helpers/site-settings";
import {
disableLoadMoreObserver,
enableLoadMoreObserver,
@@ -60,11 +63,10 @@ import {
enableVirtualization,
} from "discourse/ui-kit/-internals/windowing/virtualizer";
-const REPORT_MEMORY = false;
let cancelled = false;
let started = false;
-function createApplication(config, settings) {
+function createApplication(config) {
const app = Application.create(config);
setApplication(app);
@@ -77,8 +79,6 @@ function createApplication(config, settings) {
app.buildInstance = () => instance;
setDefaultOwner(app.__container__);
- SiteSettingService.create = () => settings;
-
if (!started) {
app.instanceInitializer({
name: "test-helper",
@@ -166,9 +166,6 @@ function setupToolbar() {
}
function reportMemoryUsageAfterTests() {
- if (!REPORT_MEMORY) {
- return;
- }
QUnit.done(() => {
const usageBytes = performance.memory?.usedJSHeapSize;
let result;
@@ -210,19 +207,9 @@ export default async function setupTests(config) {
// Stop the message bus so we don't get ajax calls
window.MessageBus.stop();
- // disable logster error reporting
- if (window.Logster) {
- window.Logster.enabled = false;
- } else {
- window.Logster = { enabled: false };
- }
-
- let setupData;
const setupDataElement = document.getElementById("data-discourse-setup");
- if (setupDataElement) {
- setupData = setupDataElement.dataset;
- setupDataElement.remove();
- }
+ const setupData = setupDataElement.dataset;
+ setupDataElement.remove();
await loadSprites(setupData.svgSpritePath, "fontawesome");
@@ -238,56 +225,59 @@ export default async function setupTests(config) {
...SYNC_OBSERVERS.keys(),
]);
- let app;
- QUnit.testStart(async function (ctx) {
- let settings = resetSettings();
-
- resetThemeSettings();
+ // Tests change settings through currentSettings(), so the service must be that object
+ SiteSettingService.create = currentSettings;
- app = createApplication(config, settings);
+ const reportRequests = getUrlParameter("report_requests") === "1";
- const cdn = setupData ? setupData.cdn : null;
- const baseUri = setupData ? setupData.baseUri : "";
- setupURL(cdn, "http://localhost:3000", baseUri, { snapshot: true });
- if (setupData && setupData.s3BaseUrl) {
- setupS3CDN(setupData.s3BaseUrl, setupData.s3Cdn, { snapshot: true });
- } else {
- setupS3CDN(null, null, { snapshot: true });
+ pretender.prepareBody = function (body) {
+ if (typeof body === "object") {
+ return JSON.stringify(body);
}
+ return body;
+ };
- applyDefaultHandlers();
-
- pretender.prepareBody = function (body) {
- if (typeof body === "object") {
- return JSON.stringify(body);
- }
- return body;
+ if (reportRequests) {
+ pretender.handledRequest = function (verb, path) {
+ // eslint-disable-next-line no-console
+ console.log("REQ: " + verb + " " + path);
};
+ }
- if (QUnit.config.logAllRequests) {
- pretender.handledRequest = function (verb, path) {
- // eslint-disable-next-line no-console
- console.log("REQ: " + verb + " " + path);
- };
+ pretender.unhandledRequest = function (verb, path) {
+ if (reportRequests) {
+ // eslint-disable-next-line no-console
+ console.log("REQ: " + verb + " " + path + " missing");
}
- pretender.unhandledRequest = function (verb, path) {
- if (QUnit.config.logAllRequests) {
- // eslint-disable-next-line no-console
- console.log("REQ: " + verb + " " + path + " missing");
- }
+ const error =
+ "Unhandled request in test environment: " + path + " (" + verb + ")";
- const error =
- "Unhandled request in test environment: " + path + " (" + verb + ")";
+ // eslint-disable-next-line no-console
+ console.error(error);
+ throw new Error(error);
+ };
- // eslint-disable-next-line no-console
- console.error(error);
- throw new Error(error);
- };
+ pretender.checkPassthrough = (request) =>
+ request.requestHeaders["Discourse-Script"];
- pretender.checkPassthrough = (request) =>
- request.requestHeaders["Discourse-Script"];
+ let app;
+ QUnit.testStart(async function (ctx) {
+ resetSettings();
+ resetThemeSettings();
+ app = createApplication(config);
+
+ setupURL(setupData.cdn, "http://localhost:3000", setupData.baseUri, {
+ snapshot: true,
+ });
+ if (setupData.s3BaseUrl) {
+ setupS3CDN(setupData.s3BaseUrl, setupData.s3Cdn, { snapshot: true });
+ } else {
+ setupS3CDN(null, null, { snapshot: true });
+ }
+
+ applyDefaultHandlers();
applyPretender(ctx.module, pretender, pretenderHelpers());
Session.resetCurrent();
@@ -400,8 +390,6 @@ export default async function setupTests(config) {
});
}
- handleLegacyParameters();
-
const hasPluginJs = !!document.querySelector(
"link[rel=modulepreload][data-plugin-name], script[data-plugin-name]"
);
@@ -418,7 +406,9 @@ export default async function setupTests(config) {
} else {
setupToolbar();
}
- reportMemoryUsageAfterTests();
+ if (getUrlParameter("report_memory") === "1") {
+ reportMemoryUsageAfterTests();
+ }
patchFailedAssertion();
setLoadedFaker(FakerModule);
@@ -463,19 +453,3 @@ function patchFailedAssertion() {
oldPushResult.call(this, resultInfo);
};
}
-
-function handleLegacyParameters() {
- for (const param of [
- "qunit_single_plugin",
- "qunit_skip_core",
- "qunit_skip_plugins",
- ]) {
- if (getUrlParameter(param)) {
- QUnit.begin(() => {
- throw new Error(
- `${param} is no longer supported. Use the 'target' parameter instead`
- );
- });
- }
- }
-}
diff --git a/spec/requests/qunit_controller_spec.rb b/spec/requests/qunit_controller_spec.rb
index 99f0073a274..21401588543 100644
--- a/spec/requests/qunit_controller_spec.rb
+++ b/spec/requests/qunit_controller_spec.rb
@@ -27,4 +27,16 @@ RSpec.describe QunitController do
get "/theme-qunit"
expect(response.status).to eq(200)
end
+
+ describe "#core" do
+ it "redirects the theme-qunit target to the theme tests page" do
+ get "/tests", params: { target: "theme-qunit" }
+ expect(response).to redirect_to("/theme-qunit")
+ end
+
+ it "returns 404 for an unknown target" do
+ get "/tests", params: { target: "missing-plugin" }
+ expect(response.status).to eq(404)
+ end
+ end
end