REFACTOR: Move test setup to a module

This is long overdue. We had a lot of (not linted) code to initialize
our test suite as part of the Ruby `test_helper.js` bundle.

This refactor moves that out to a `setup-tests` module, which imports
all the modules properly, rather than using `require`.

It also removes the global `server` variable which some tests were using
for pretender. Those tests are fixed, and in the case of widget tests,
support for a `pretend()` was added, which mimics our acceptance tests.

One problematic test was removed, which overwrites `/posts` - this could
break tons of other tests depending on order.
This commit is contained in:
Robin Ward 2020-10-07 17:08:19 -04:00
parent 5130b4d674
commit ef7d99b0a8
12 changed files with 563 additions and 566 deletions

View File

@ -18,143 +18,7 @@ acceptance("Composer Actions", {
site: {
can_tag_topics: true,
},
});
test("creating new topic and then reply_as_private_message keeps attributes", async (assert) => {
await visit("/");
await click("button#create-topic");
await fillIn("#reply-title", "this is the title");
await fillIn(".d-editor-input", "this is the reply");
const composerActions = selectKit(".composer-actions");
await composerActions.expand();
await composerActions.selectRowByValue("reply_as_private_message");
assert.ok(find("#reply-title").val(), "this is the title");
assert.ok(find(".d-editor-input").val(), "this is the reply");
});
test("replying to post", async (assert) => {
const composerActions = selectKit(".composer-actions");
await visit("/t/internationalization-localization/280");
await click("article#post_3 button.reply");
await composerActions.expand();
assert.equal(composerActions.rowByIndex(0).value(), "reply_as_new_topic");
assert.equal(
composerActions.rowByIndex(1).value(),
"reply_as_private_message"
);
assert.equal(composerActions.rowByIndex(2).value(), "reply_to_topic");
assert.equal(composerActions.rowByIndex(3).value(), "toggle_whisper");
assert.equal(composerActions.rowByIndex(4).value(), "toggle_topic_bump");
assert.equal(composerActions.rowByIndex(5).value(), undefined);
});
test("replying to post - reply_as_private_message", async (assert) => {
const composerActions = selectKit(".composer-actions");
await visit("/t/internationalization-localization/280");
await click("article#post_3 button.reply");
await composerActions.expand();
await composerActions.selectRowByValue("reply_as_private_message");
assert.equal(find(".users-input .item:eq(0)").text(), "codinghorror");
assert.ok(
find(".d-editor-input").val().indexOf("Continuing the discussion") >= 0
);
});
test("replying to post - reply_to_topic", async (assert) => {
const composerActions = selectKit(".composer-actions");
await visit("/t/internationalization-localization/280");
await click("article#post_3 button.reply");
await fillIn(
".d-editor-input",
"test replying to topic when initially replied to post"
);
await composerActions.expand();
await composerActions.selectRowByValue("reply_to_topic");
assert.equal(
find(".action-title .topic-link").text().trim(),
"Internationalization / localization"
);
assert.equal(
find(".action-title .topic-link").attr("href"),
"/t/internationalization-localization/280"
);
assert.equal(
find(".d-editor-input").val(),
"test replying to topic when initially replied to post"
);
});
test("replying to post - toggle_whisper", async (assert) => {
const composerActions = selectKit(".composer-actions");
await visit("/t/internationalization-localization/280");
await click("article#post_3 button.reply");
await fillIn(
".d-editor-input",
"test replying as whisper to topic when initially not a whisper"
);
await composerActions.expand();
await composerActions.selectRowByValue("toggle_whisper");
assert.ok(
find(".composer-fields .whisper .d-icon-far-eye-slash").length === 1
);
});
test("replying to post - reply_as_new_topic", async (assert) => {
sandbox
.stub(Draft, "get")
.returns(Promise.resolve({ draft: "", draft_sequence: 0 }));
const composerActions = selectKit(".composer-actions");
const categoryChooser = selectKit(".title-wrapper .category-chooser");
const categoryChooserReplyArea = selectKit(".reply-area .category-chooser");
const quote = "test replying as new topic when initially replied to post";
await visit("/t/internationalization-localization/280");
await click("#topic-title .d-icon-pencil-alt");
await categoryChooser.expand();
await categoryChooser.selectRowByValue(4);
await click("#topic-title .submit-edit");
await click("article#post_3 button.reply");
await fillIn(".d-editor-input", quote);
await composerActions.expand();
await composerActions.selectRowByValue("reply_as_new_topic");
assert.equal(categoryChooserReplyArea.header().name(), "faq");
assert.equal(
find(".action-title").text().trim(),
I18n.t("topic.create_long")
);
assert.ok(find(".d-editor-input").val().includes(quote));
sandbox.restore();
});
test("reply_as_new_topic without a new_topic draft", async (assert) => {
await visit("/t/internationalization-localization/280");
await click(".create.reply");
const composerActions = selectKit(".composer-actions");
await composerActions.expand();
await composerActions.selectRowByValue("reply_as_new_topic");
assert.equal(exists(find(".bootbox")), false);
});
test("reply_as_new_group_message", async (assert) => {
// eslint-disable-next-line
pretend(server) {
server.get("/t/130.json", () => {
return [
200,
@ -391,7 +255,143 @@ test("reply_as_new_group_message", async (assert) => {
},
];
});
},
});
test("creating new topic and then reply_as_private_message keeps attributes", async (assert) => {
await visit("/");
await click("button#create-topic");
await fillIn("#reply-title", "this is the title");
await fillIn(".d-editor-input", "this is the reply");
const composerActions = selectKit(".composer-actions");
await composerActions.expand();
await composerActions.selectRowByValue("reply_as_private_message");
assert.ok(find("#reply-title").val(), "this is the title");
assert.ok(find(".d-editor-input").val(), "this is the reply");
});
test("replying to post", async (assert) => {
const composerActions = selectKit(".composer-actions");
await visit("/t/internationalization-localization/280");
await click("article#post_3 button.reply");
await composerActions.expand();
assert.equal(composerActions.rowByIndex(0).value(), "reply_as_new_topic");
assert.equal(
composerActions.rowByIndex(1).value(),
"reply_as_private_message"
);
assert.equal(composerActions.rowByIndex(2).value(), "reply_to_topic");
assert.equal(composerActions.rowByIndex(3).value(), "toggle_whisper");
assert.equal(composerActions.rowByIndex(4).value(), "toggle_topic_bump");
assert.equal(composerActions.rowByIndex(5).value(), undefined);
});
test("replying to post - reply_as_private_message", async (assert) => {
const composerActions = selectKit(".composer-actions");
await visit("/t/internationalization-localization/280");
await click("article#post_3 button.reply");
await composerActions.expand();
await composerActions.selectRowByValue("reply_as_private_message");
assert.equal(find(".users-input .item:eq(0)").text(), "codinghorror");
assert.ok(
find(".d-editor-input").val().indexOf("Continuing the discussion") >= 0
);
});
test("replying to post - reply_to_topic", async (assert) => {
const composerActions = selectKit(".composer-actions");
await visit("/t/internationalization-localization/280");
await click("article#post_3 button.reply");
await fillIn(
".d-editor-input",
"test replying to topic when initially replied to post"
);
await composerActions.expand();
await composerActions.selectRowByValue("reply_to_topic");
assert.equal(
find(".action-title .topic-link").text().trim(),
"Internationalization / localization"
);
assert.equal(
find(".action-title .topic-link").attr("href"),
"/t/internationalization-localization/280"
);
assert.equal(
find(".d-editor-input").val(),
"test replying to topic when initially replied to post"
);
});
test("replying to post - toggle_whisper", async (assert) => {
const composerActions = selectKit(".composer-actions");
await visit("/t/internationalization-localization/280");
await click("article#post_3 button.reply");
await fillIn(
".d-editor-input",
"test replying as whisper to topic when initially not a whisper"
);
await composerActions.expand();
await composerActions.selectRowByValue("toggle_whisper");
assert.ok(
find(".composer-fields .whisper .d-icon-far-eye-slash").length === 1
);
});
test("replying to post - reply_as_new_topic", async (assert) => {
sandbox
.stub(Draft, "get")
.returns(Promise.resolve({ draft: "", draft_sequence: 0 }));
const composerActions = selectKit(".composer-actions");
const categoryChooser = selectKit(".title-wrapper .category-chooser");
const categoryChooserReplyArea = selectKit(".reply-area .category-chooser");
const quote = "test replying as new topic when initially replied to post";
await visit("/t/internationalization-localization/280");
await click("#topic-title .d-icon-pencil-alt");
await categoryChooser.expand();
await categoryChooser.selectRowByValue(4);
await click("#topic-title .submit-edit");
await click("article#post_3 button.reply");
await fillIn(".d-editor-input", quote);
await composerActions.expand();
await composerActions.selectRowByValue("reply_as_new_topic");
assert.equal(categoryChooserReplyArea.header().name(), "faq");
assert.equal(
find(".action-title").text().trim(),
I18n.t("topic.create_long")
);
assert.ok(find(".d-editor-input").val().includes(quote));
sandbox.restore();
});
test("reply_as_new_topic without a new_topic draft", async (assert) => {
await visit("/t/internationalization-localization/280");
await click(".create.reply");
const composerActions = selectKit(".composer-actions");
await composerActions.expand();
await composerActions.selectRowByValue("reply_as_new_topic");
assert.equal(exists(find(".bootbox")), false);
});
test("reply_as_new_group_message", async (assert) => {
await visit("/t/lorem-ipsum-dolor-sit-amet/130");
await click(".create.reply");
const composerActions = selectKit(".composer-actions");

View File

@ -10,8 +10,8 @@ import { Promise } from "rsvp";
acceptance("Composer", {
loggedIn: true,
pretend(pretenderServer, helper) {
pretenderServer.post("/uploads/lookup-urls", () => {
pretend(server, helper) {
server.post("/uploads/lookup-urls", () => {
return helper.response([]);
});
},
@ -810,20 +810,3 @@ test("Image resizing buttons", async (assert) => {
"it does not unescapes script tags in code blocks"
);
});
test("can reply to a private message", async (assert) => {
let submitted;
/* global server */
server.post("/posts", () => {
submitted = true;
return [200, { "Content-Type": "application/json" }, {}];
});
await visit("/t/34");
await click(".topic-post:eq(0) button.reply");
await fillIn(".d-editor-input", "this is the *content* of the reply");
await click("#reply-control button.create");
assert.ok(submitted);
});

View File

@ -41,6 +41,10 @@ export let fixturesByUrl;
export default new Pretender();
export function pretenderHelpers() {
return { parsePostData, response, success };
}
export function applyDefaultHandlers(pretender) {
// Autoload any `*-pretender` files
Object.keys(requirejs.entries).forEach((e) => {

View File

@ -1,8 +1,6 @@
import { Promise } from "rsvp";
import { isEmpty } from "@ember/utils";
import { later } from "@ember/runloop";
/* global QUnit, resetSite */
import sessionFixtures from "discourse/tests/fixtures/session-fixtures";
import HeaderComponent from "discourse/components/site-header";
import { forceMobile, resetMobile } from "discourse/lib/mobile";
@ -36,7 +34,10 @@ import { setURLContainer } from "discourse/lib/url";
import { setDefaultOwner } from "discourse-common/lib/get-owner";
import bootbox from "bootbox";
import { moduleFor } from "ember-qunit";
import { module } from "qunit";
import QUnit, { module } from "qunit";
import siteFixtures from "discourse/tests/fixtures/site-fixtures";
import Site from "discourse/models/site";
import createStore from "discourse/tests/helpers/create-store";
export function currentUser() {
return User.create(sessionFixtures["/session/current.json"].current_user);
@ -114,6 +115,13 @@ $.fn.modal = AcceptanceModal;
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) {
@ -152,14 +160,19 @@ export function discourseModule(name, hooks) {
});
}
export function acceptance(name, options) {
options = options || {};
if (options.pretend) {
_pretenderCallbacks[name] = options.pretend;
export function addPretenderCallback(name, fn) {
if (name && fn) {
_pretenderCallbacks[name] = fn;
}
}
module("Acceptance: " + name, {
export function acceptance(name, options) {
name = `Acceptance: ${name}`;
options = options || {};
addPretenderCallback(name, options.pretend);
module(name, {
beforeEach() {
resetMobile();

View File

@ -1,10 +1,14 @@
import { moduleForComponent } from "ember-qunit";
import componentTest from "discourse/tests/helpers/component-test";
import { addPretenderCallback } from "discourse/tests/helpers/qunit-helpers";
export function moduleForWidget(name, options = {}) {
let fullName = `widget:${name}`;
addPretenderCallback(fullName, options.pretend);
moduleForComponent(
name,
`widget:${name}`,
fullName,
Object.assign(
{ integration: true },
{ beforeEach: options.beforeEach, afterEach: options.afterEach }

View File

@ -0,0 +1,189 @@
import {
resetSettings,
currentSettings,
} from "discourse/tests/helpers/site-settings";
import { getOwner, setDefaultOwner } from "discourse-common/lib/get-owner";
import { setupURL, setupS3CDN } from "discourse-common/lib/get-url";
import { createHelperContext } from "discourse-common/lib/helpers";
import { buildResolver } from "discourse-common/resolver";
import createPretender, {
pretenderHelpers,
applyDefaultHandlers,
} from "discourse/tests/helpers/create-pretender";
import { flushMap } from "discourse/models/store";
import { ScrollingDOMMethods } from "discourse/mixins/scrolling";
import DiscourseURL from "discourse/lib/url";
import {
resetSite,
applyPretender,
} from "discourse/tests/helpers/qunit-helpers";
import PreloadStore from "discourse/lib/preload-store";
import User from "discourse/models/user";
import Session from "discourse/models/session";
import { clearAppEventsCache } from "discourse/services/app-events";
import QUnit from "qunit";
import MessageBus from "message-bus-client";
import deprecated from "discourse-common/lib/deprecated";
export default function setupTests(App) {
window.setResolver(buildResolver("discourse").create({ namespace: App }));
sinon.config = {
injectIntoThis: false,
injectInto: null,
properties: ["spy", "stub", "mock", "clock", "sandbox"],
useFakeTimers: true,
useFakeServer: false,
};
// Stop the message bus so we don't get ajax calls
MessageBus.stop();
document.write(
'<div id="ember-testing-container"><div id="ember-testing"></div></div>'
);
document.write(
"<style>#ember-testing-container { position: absolute; background: white; bottom: 0; right: 0; width: 640px; height: 384px; overflow: auto; z-index: 9999; border: 1px solid #ccc; } #ember-testing { zoom: 50%; }</style>"
);
App.rootElement = "#ember-testing";
App.setupForTesting();
App.injectTestHelpers();
App.SiteSettings = currentSettings();
App.start();
// disable logster error reporting
if (window.Logster) {
window.Logster.enabled = false;
} else {
window.Logster = { enabled: false };
}
let server;
Object.defineProperty(window, "server", {
get() {
deprecated(
"Accessing the global variable `server` is deprecated. Use a `pretend()` method instead.",
{
since: "2.6.0.beta.3",
dropFrom: "2.6.0",
}
);
return server;
},
});
QUnit.testStart(function (ctx) {
let settings = resetSettings();
server = createPretender;
applyDefaultHandlers(server);
server.handlers = [];
server.prepareBody = function (body) {
if (body && typeof body === "object") {
return JSON.stringify(body);
}
return body;
};
if (QUnit.config.logAllRequests) {
server.handledRequest = function (verb, path) {
// eslint-disable-next-line no-console
console.log("REQ: " + verb + " " + path);
};
}
server.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 + ")";
window.console.error(error);
throw new Error(error);
};
server.checkPassthrough = (request) =>
request.requestHeaders["Discourse-Script"];
applyPretender(ctx.module, server, pretenderHelpers());
setupURL(null, "http://localhost:3000", "");
setupS3CDN(null, null);
Session.resetCurrent();
User.resetCurrent();
let site = resetSite(settings);
createHelperContext({
siteSettings: settings,
capabilities: {},
site,
});
DiscourseURL.redirectedTo = null;
DiscourseURL.redirectTo = function (url) {
DiscourseURL.redirectedTo = url;
};
PreloadStore.reset();
window.sandbox = sinon;
window.sandbox.stub(ScrollingDOMMethods, "screenNotFull");
window.sandbox.stub(ScrollingDOMMethods, "bindOnScroll");
window.sandbox.stub(ScrollingDOMMethods, "unbindOnScroll");
// Unless we ever need to test this, let's leave it off.
$.fn.autocomplete = function () {};
});
QUnit.testDone(function () {
window.sandbox.restore();
// Destroy any modals
$(".modal-backdrop").remove();
flushMap();
// ensures any event not removed is not leaking between tests
// most likely in intialisers, other places (controller, component...)
// should be fixed in code
clearAppEventsCache(getOwner(this));
MessageBus.unsubscribe("*");
server = null;
window.Mousetrap.reset();
});
// Load ES6 tests
function getUrlParameter(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(location.search);
return results === null
? ""
: decodeURIComponent(results[1].replace(/\+/g, " "));
}
let skipCore = getUrlParameter("qunit_skip_core") === "1";
let pluginPath = getUrlParameter("qunit_single_plugin")
? "/" + getUrlParameter("qunit_single_plugin") + "/"
: "/plugins/";
Object.keys(requirejs.entries).forEach(function (entry) {
let isTest = /\-test/.test(entry);
let regex = new RegExp(pluginPath);
let isPlugin = regex.test(entry);
if (isTest && (!skipCore || isPlugin)) {
require(entry, null, null, true);
}
});
// forces 0 as duration for all jquery animations
jQuery.fx.off = true;
setDefaultOwner(App.__container__);
resetSite();
}

View File

@ -40,208 +40,10 @@
//= require_tree ./unit
//= require_tree ../../admin/tests/admin
//= require plugin_tests
//= require setup-tests
//= require_self
//
//= require jquery.magnific-popup.min.js
let App = window.Discourse;
let {
resetSettings,
currentSettings,
} = require("discourse/tests/helpers/site-settings");
let createHelperContext = require("discourse-common/lib/helpers")
.createHelperContext;
const buildResolver = require("discourse-common/resolver").buildResolver;
window.setResolver(buildResolver("discourse").create({ namespace: App }));
sinon.config = {
injectIntoThis: false,
injectInto: null,
properties: ["spy", "stub", "mock", "clock", "sandbox"],
useFakeTimers: true,
useFakeServer: false,
};
let MessageBus = require("message-bus-client").default;
// Stop the message bus so we don't get ajax calls
MessageBus.stop();
// Trick JSHint into allow document.write
var d = document;
d.write(
'<div id="ember-testing-container"><div id="ember-testing"></div></div>'
);
d.write(
"<style>#ember-testing-container { position: absolute; background: white; bottom: 0; right: 0; width: 640px; height: 384px; overflow: auto; z-index: 9999; border: 1px solid #ccc; } #ember-testing { zoom: 50%; }</style>"
);
App.rootElement = "#ember-testing";
App.setupForTesting();
App.injectTestHelpers();
App.SiteSettings = currentSettings();
App.start();
// disable logster error reporting
if (window.Logster) {
Logster.enabled = false;
} else {
window.Logster = { enabled: false };
}
var createPretender = require("discourse/tests/helpers/create-pretender", null, null, false),
siteFixtures = require("discourse/tests/fixtures/site-fixtures", null, null, false)
.default,
flushMap = require("discourse/models/store", null, null, false).flushMap,
ScrollingDOMMethods = require("discourse/mixins/scrolling", null, null, false)
.ScrollingDOMMethods,
_DiscourseURL = require("discourse/lib/url", null, null, false).default,
applyPretender = require("discourse/tests/helpers/qunit-helpers", null, null, false)
.applyPretender,
getOwner = require("discourse-common/lib/get-owner").getOwner,
setDefaultOwner = require("discourse-common/lib/get-owner").setDefaultOwner,
server,
acceptanceModulePrefix = "Acceptance: ";
function dup(obj) {
return jQuery.extend(true, {}, obj);
}
function resetSite(siteSettings, extras) {
let createStore = require("discourse/tests/helpers/create-store").default;
let siteAttrs = $.extend({}, siteFixtures["site.json"].site, extras || {});
let Site = require("discourse/models/site").default;
siteAttrs.store = createStore();
siteAttrs.siteSettings = siteSettings;
return Site.resetCurrent(Site.create(siteAttrs));
}
QUnit.testStart(function (ctx) {
let settings = resetSettings();
server = createPretender.default;
createPretender.applyDefaultHandlers(server);
server.handlers = [];
server.prepareBody = function (body) {
if (body && typeof body === "object") {
return JSON.stringify(body);
}
return body;
};
if (QUnit.config.logAllRequests) {
server.handledRequest = function (verb, path, request) {
console.log("REQ: " + verb + " " + path);
};
}
server.unhandledRequest = function (verb, path) {
if (QUnit.config.logAllRequests) {
console.log("REQ: " + verb + " " + path + " missing");
}
const error =
"Unhandled request in test environment: " + path + " (" + verb + ")";
window.console.error(error);
throw new Error(error);
};
server.checkPassthrough = (request) =>
request.requestHeaders["Discourse-Script"];
if (ctx.module.startsWith(acceptanceModulePrefix)) {
var helper = {
parsePostData: createPretender.parsePostData,
response: createPretender.response,
success: createPretender.success,
};
applyPretender(
ctx.module.replace(acceptanceModulePrefix, ""),
server,
helper
);
}
let getURL = require("discourse-common/lib/get-url");
getURL.setupURL(null, "http://localhost:3000", "");
getURL.setupS3CDN(null, null);
let User = require("discourse/models/user").default;
let Session = require("discourse/models/session").default;
Session.resetCurrent();
User.resetCurrent();
let site = resetSite(settings);
createHelperContext({
siteSettings: settings,
capabilities: {},
site,
});
_DiscourseURL.redirectedTo = null;
_DiscourseURL.redirectTo = function (url) {
_DiscourseURL.redirectedTo = url;
};
var ps = require("discourse/lib/preload-store").default;
ps.reset();
window.sandbox = sinon;
window.sandbox.stub(ScrollingDOMMethods, "screenNotFull");
window.sandbox.stub(ScrollingDOMMethods, "bindOnScroll");
window.sandbox.stub(ScrollingDOMMethods, "unbindOnScroll");
// Unless we ever need to test this, let's leave it off.
$.fn.autocomplete = function () {};
});
QUnit.testDone(function () {
window.sandbox.restore();
// Destroy any modals
$(".modal-backdrop").remove();
flushMap();
// ensures any event not removed is not leaking between tests
// most likely in intialisers, other places (controller, component...)
// should be fixed in code
require("discourse/services/app-events").clearAppEventsCache(getOwner(this));
MessageBus.unsubscribe("*");
delete window.server;
window.Mousetrap.reset();
});
// Load ES6 tests
var helpers = require("discourse/tests/helpers/qunit-helpers");
function getUrlParameter(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(location.search);
return results === null
? ""
: decodeURIComponent(results[1].replace(/\+/g, " "));
}
var skipCore = getUrlParameter("qunit_skip_core") == "1";
var pluginPath = getUrlParameter("qunit_single_plugin")
? "/" + getUrlParameter("qunit_single_plugin") + "/"
: "/plugins/";
Object.keys(requirejs.entries).forEach(function (entry) {
var isTest = /\-test/.test(entry);
var regex = new RegExp(pluginPath);
var isPlugin = regex.test(entry);
if (isTest && (!skipCore || isPlugin)) {
require(entry, null, null, true);
}
});
// forces 0 as duration for all jquery animations
jQuery.fx.off = true;
setDefaultOwner(App.__container__);
resetSite();
let setupTests = require("discourse/tests/setup-tests").default;
setupTests(window.Discourse);

View File

@ -62,7 +62,7 @@ function stubUrls(imageSrcs, attachmentSrcs, otherMediaSrcs) {
];
}
// prettier-ignore
pretender.post("/uploads/lookup-urls", () => { //eslint-disable-line
pretender.post("/uploads/lookup-urls", () => {
return response(imageSrcs.concat(attachmentSrcs.concat(otherMediaSrcs)));
});

View File

@ -1,6 +1,6 @@
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
acceptance("Rendering polls with pie charts - desktop", {
acceptance("Rendering polls with pie charts", {
loggedIn: true,
settings: { poll_enabled: true, poll_groupable_user_fields: "something" },
});

View File

@ -7,6 +7,37 @@ acceptance("Rendering polls with bar charts - desktop", {
beforeEach() {
clearPopupMenuOptionsCallback();
},
pretend(server) {
server.get("/polls/voters.json", (request) => {
let body = {};
if (
request.queryParams.option_id === "68b434ff88aeae7054e42cd05a4d9056"
) {
body = {
voters: {
"68b434ff88aeae7054e42cd05a4d9056": [
{
id: 777,
username: "bruce777",
avatar_template: "/images/avatar.png",
name: "Bruce Wayne",
},
],
},
};
} else {
body = {
voters: Array.from(new Array(5), (_, i) => ({
id: 600 + i,
username: `bruce${600 + i}`,
avatar_template: "/images/avatar.png",
name: "Bruce Wayne",
})),
};
}
return [200, { "Content-Type": "application/json" }, body];
});
},
});
test("Polls", async (assert) => {
@ -43,24 +74,6 @@ test("Public poll", async (assert) => {
"it should display the right number of voters"
);
// eslint-disable-next-line
server.get("/polls/voters.json", () => {
const body = {
voters: {
"68b434ff88aeae7054e42cd05a4d9056": [
{
id: 777,
username: "bruce777",
avatar_template: "/images/avatar.png",
name: "Bruce Wayne",
},
],
},
};
return [200, { "Content-Type": "application/json" }, body];
});
await click(".poll-voters-toggle-expand:first a");
assert.equal(
@ -89,20 +102,6 @@ test("Public number poll", async (assert) => {
"user URL does not exist"
);
// eslint-disable-next-line
server.get("/polls/voters.json", () => {
const body = {
voters: Array.from(new Array(5), (_, i) => ({
id: 600 + i,
username: `bruce${600 + i}`,
avatar_template: "/images/avatar.png",
name: "Bruce Wayne",
})),
};
return [200, { "Content-Type": "application/json" }, body];
});
await click(".poll-voters-toggle-expand:first a");
assert.equal(

View File

@ -8,6 +8,21 @@ acceptance("Rendering polls with bar charts - mobile", {
beforeEach() {
clearPopupMenuOptionsCallback();
},
pretend(server) {
// eslint-disable-next-line
server.get("/polls/voters.json", () => {
const body = {
voters: Array.from(new Array(10), (_, i) => ({
id: 500 + i,
username: `bruce${500 + i}`,
avatar_template: "/images/avatar.png",
name: "Bruce Wayne",
})),
};
return [200, { "Content-Type": "application/json" }, body];
});
},
});
test("Public number poll", async (assert) => {
@ -29,20 +44,6 @@ test("Public number poll", async (assert) => {
"user URL does not exist"
);
// eslint-disable-next-line
server.get("/polls/voters.json", () => {
const body = {
voters: Array.from(new Array(10), (_, i) => ({
id: 500 + i,
username: `bruce${500 + i}`,
avatar_template: "/images/avatar.png",
name: "Bruce Wayne",
})),
};
return [200, { "Content-Type": "application/json" }, body];
});
await click(".poll-voters-toggle-expand:first a");
assert.equal(

View File

@ -5,7 +5,58 @@ import {
widgetTest,
} from "discourse/tests/helpers/widget-test";
moduleForWidget("discourse-poll");
let requests = 0;
moduleForWidget("discourse-poll", {
pretend(server) {
server.put("/polls/vote", () => {
++requests;
return [
200,
{ "Content-Type": "application/json" },
{
poll: {
name: "poll",
type: "regular",
status: "open",
results: "always",
options: [
{ id: "1f972d1df351de3ce35a787c89faad29", html: "yes", votes: 1 },
{ id: "d7ebc3a9beea2e680815a1e4f57d6db6", html: "no", votes: 0 },
],
voters: 1,
chart_type: "bar",
},
vote: ["1f972d1df351de3ce35a787c89faad29"],
},
];
});
server.put("/polls/vote", () => {
++requests;
return [
200,
{ "Content-Type": "application/json" },
{
poll: {
name: "poll",
type: "regular",
status: "open",
results: "always",
options: [
{ id: "1f972d1df351de3ce35a787c89faad29", html: "yes", votes: 1 },
{ id: "d7ebc3a9beea2e680815a1e4f57d6db6", html: "no", votes: 0 },
],
voters: 1,
chart_type: "bar",
groups: "foo",
},
vote: ["1f972d1df351de3ce35a787c89faad29"],
},
];
});
},
});
const template = `{{mount-widget
widget="discourse-poll"
@ -44,31 +95,7 @@ widgetTest("can vote", {
},
async test(assert) {
let requests = 0;
/* global server */
server.put("/polls/vote", () => {
++requests;
return [
200,
{ "Content-Type": "application/json" },
{
poll: {
name: "poll",
type: "regular",
status: "open",
results: "always",
options: [
{ id: "1f972d1df351de3ce35a787c89faad29", html: "yes", votes: 1 },
{ id: "d7ebc3a9beea2e680815a1e4f57d6db6", html: "no", votes: 0 },
],
voters: 1,
chart_type: "bar",
},
vote: ["1f972d1df351de3ce35a787c89faad29"],
},
];
});
requests = 0;
await click("li[data-poll-option-id='1f972d1df351de3ce35a787c89faad29']");
assert.equal(requests, 1);
@ -115,32 +142,7 @@ widgetTest("cannot vote if not member of the right group", {
},
async test(assert) {
let requests = 0;
/* global server */
server.put("/polls/vote", () => {
++requests;
return [
200,
{ "Content-Type": "application/json" },
{
poll: {
name: "poll",
type: "regular",
status: "open",
results: "always",
options: [
{ id: "1f972d1df351de3ce35a787c89faad29", html: "yes", votes: 1 },
{ id: "d7ebc3a9beea2e680815a1e4f57d6db6", html: "no", votes: 0 },
],
voters: 1,
chart_type: "bar",
groups: "foo",
},
vote: ["1f972d1df351de3ce35a787c89faad29"],
},
];
});
requests = 0;
await click("li[data-poll-option-id='1f972d1df351de3ce35a787c89faad29']");
assert.equal(