{% for reaction in comment.reactions.all %}
{% if reaction.counter > 0 %}
@@ -21,4 +21,4 @@
{% endwith %}
{% endif %}
{% endfor %}
-
\ No newline at end of file
+
diff --git a/django_comments_xtd/templates/comments/form.html b/django_comments_xtd/templates/comments/form.html
index eecfe9b1..58b17e45 100644
--- a/django_comments_xtd/templates/comments/form.html
+++ b/django_comments_xtd/templates/comments/form.html
@@ -58,8 +58,8 @@
-
-
+
+
diff --git a/django_comments_xtd/templates/comments/list.html b/django_comments_xtd/templates/comments/list.html
index 96c8d8a6..19523925 100644
--- a/django_comments_xtd/templates/comments/list.html
+++ b/django_comments_xtd/templates/comments/list.html
@@ -6,15 +6,19 @@
id="comments"
class="comment-list"
{% if comment_reactions_enabled %}
- data-type="reactions-def"
+ data-dcx="config"
data-reactions="{% reactions_enum_strlist %}"
{% if user.is_authenticated %}
data-reactions-url="{% url 'comments-xtd-api-react' %}"
{% endif %}
+ data-guest-user="{% if user.is_authenticated %}0{% else %}1{% endif %}"
data-reactions-row-length="4"
data-reactions-header-title="{% trans 'Pick your reaction' %}"
- data-pos-bottom="{{ reactions_popover_pos_bottom }}"
- data-pos-left="{{ reactions_popover_pos_left }}"
+ data-popover-pos-bottom="{{ reactions_popover_pos_bottom }}"
+ data-popover-pos-left="{{ reactions_popover_pos_left }}"
+ data-tooltip-pos-bottom="{{ reactions_tooltip_pos_bottom }}"
+ data-tooltip-pos-left="{{ reactions_tooltip_pos_left }}"
+ data-page-qs-param="{{ comments_page_qs_param }}"
{% endif %}
>
{% if is_paginated %}
diff --git a/django_comments_xtd/templatetags/comments_xtd.py b/django_comments_xtd/templatetags/comments_xtd.py
index 3646c59e..504b303d 100644
--- a/django_comments_xtd/templatetags/comments_xtd.py
+++ b/django_comments_xtd/templatetags/comments_xtd.py
@@ -490,7 +490,6 @@ def get_comment(comment_id: str):
@register.simple_tag()
def dcx_custom_selector():
- print(f"custom_selector: {settings.COMMENTS_XTD_CSS_CUSTOM_SELECTOR}")
return f"{settings.COMMENTS_XTD_CSS_CUSTOM_SELECTOR}"
diff --git a/django_comments_xtd/tests/templates/my_comments/list.html b/django_comments_xtd/tests/templates/my_comments/list.html
index a03016fa..9728efd6 100644
--- a/django_comments_xtd/tests/templates/my_comments/list.html
+++ b/django_comments_xtd/tests/templates/my_comments/list.html
@@ -6,15 +6,19 @@
id="comments"
class="comment-list"
{% if comment_reactions_enabled %}
- data-type="reactions-def"
+ data-dcx="config"
data-reactions="{% reactions_enum_strlist %}"
{% if user.is_authenticated %}
data-reactions-url="{% url 'comments-xtd-api-react' %}"
{% endif %}
+ data-guest-user="{% if user.is_authenticated %}0{% else %}1{% endif %}"
data-reactions-row-length="4"
data-reactions-header-title="{% trans 'Pick your reaction' %}"
- data-pos-bottom="{{ reactions_popover_pos_bottom }}"
- data-pos-left="{{ reactions_popover_pos_left }}"
+ data-popover-pos-bottom="{{ reactions_popover_pos_bottom }}"
+ data-popover-pos-left="{{ reactions_popover_pos_left }}"
+ data-tooltip-pos-bottom="{{ reactions_tooltip_pos_bottom }}"
+ data-tooltip-pos-left="{{ reactions_tooltip_pos_left }}"
+ data-page-qs-param="{{ comments_page_qs_param }}"
{% endif %}
>
{% if is_paginated %}
@@ -66,4 +70,4 @@
{% if is_paginated %}
{% include "comments/pagination.html" %}
{% endif %}
-
\ No newline at end of file
+
diff --git a/django_comments_xtd/views.py b/django_comments_xtd/views.py
index f4a65430..d8d5ea88 100644
--- a/django_comments_xtd/views.py
+++ b/django_comments_xtd/views.py
@@ -232,14 +232,21 @@ def post_js(request, next=None, using=None):
except ObjectDoesNotExist:
error_msg = (
"No object matching content-type %r and object PK %r exists."
- % (escape(ctype), escape(object_pk))
+ % (
+ escape(ctype),
+ escape(object_pk),
+ )
)
context = {"bad_error": error_msg}
return json_res(request, "comments/bad_form.html", context, status=400)
except (ValueError, ValidationError) as e:
error_msg = (
"Attempting to get content-type %r and object PK %r raised %s"
- % (escape(ctype), escape(object_pk), e.__class__.__name__)
+ % (
+ escape(ctype),
+ escape(object_pk),
+ e.__class__.__name__,
+ )
)
context = {"bad_error": error_msg}
return json_res(request, "comments/bad_form.html", context, status=400)
@@ -497,7 +504,6 @@ def sent_js(request, comment, using=None):
target = model._default_manager.using(using).get(pk=object_pk)
except Exception:
context = {"bad_error": "Comment does not exist."}
- print("Returning bad_form in sent_js.")
return json_res(
request, "comments/bad_form.html", context, status=400
)
@@ -526,7 +532,6 @@ def sent_js(request, comment, using=None):
request, comment.content_type.id, comment.object_pk, comment.id
)
comment_url = get_comment_url(comment, None, page_number)
- print("Returning published_tmpl.")
return json_res(
request,
published_tmpl,
@@ -541,7 +546,6 @@ def sent_js(request, comment, using=None):
% comment.content_type.app_label,
"comments/moderated_js.html",
]
- print("Returning moderated_tmpl.")
return json_res(
request, moderated_tmpl, {"comment": comment}, status=201
)
diff --git a/jest.config.js b/jest.config.js
new file mode 100644
index 00000000..12e34b3c
--- /dev/null
+++ b/jest.config.js
@@ -0,0 +1,194 @@
+/*
+ * For a detailed explanation regarding each configuration property, visit:
+ * https://jestjs.io/docs/configuration
+ */
+
+module.exports = {
+ // All imported modules in your tests should be mocked automatically
+ // automock: false,
+
+ // Stop running tests after `n` failures
+ // bail: 0,
+
+ // The directory where Jest should store its cached dependency information
+ // cacheDirectory: "/private/var/folders/b8/kt0gzxn107d3p1m78sc42bnw0000gn/T/jest_dx",
+
+ // Automatically clear mock calls, instances and results before every test
+ // clearMocks: false,
+
+ // Indicates whether the coverage information should be collected while executing the test
+ // collectCoverage: false,
+
+ // An array of glob patterns indicating a set of files for which coverage information should be collected
+ // collectCoverageFrom: undefined,
+
+ // The directory where Jest should output its coverage files
+ // coverageDirectory: "coverage",
+
+ // An array of regexp pattern strings used to skip coverage collection
+ // coveragePathIgnorePatterns: [
+ // "/node_modules/"
+ // ],
+
+ // Indicates which provider should be used to instrument code for coverage
+ // coverageProvider: "babel",
+
+ // A list of reporter names that Jest uses when writing coverage reports
+ // coverageReporters: [
+ // "json",
+ // "text",
+ // "lcov",
+ // "clover"
+ // ],
+
+ // An object that configures minimum threshold enforcement for coverage results
+ // coverageThreshold: undefined,
+
+ // A path to a custom dependency extractor
+ // dependencyExtractor: undefined,
+
+ // Make calling deprecated APIs throw helpful error messages
+ // errorOnDeprecated: false,
+
+ // Force coverage collection from ignored files using an array of glob patterns
+ // forceCoverageMatch: [],
+
+ // A path to a module which exports an async function that is triggered once before all test suites
+ globalSetup: "/global-setup.js",
+
+ // A path to a module which exports an async function that is triggered once after all test suites
+ globalTeardown: "/global-teardown.js",
+
+ // A set of global variables that need to be available in all test environments
+ // globals: {},
+
+ // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
+ // maxWorkers: "50%",
+
+ // An array of directory names to be searched recursively up from the requiring module's location
+ // moduleDirectories: [
+ // "node_modules"
+ // ],
+
+ // An array of file extensions your modules use
+ // moduleFileExtensions: [
+ // "js",
+ // "jsx",
+ // "ts",
+ // "tsx",
+ // "json",
+ // "node"
+ // ],
+
+ // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
+ // moduleNameMapper: {},
+
+ // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
+ // modulePathIgnorePatterns: [],
+
+ // Activates notifications for test results
+ // notify: false,
+
+ // An enum that specifies notification mode. Requires { notify: true }
+ // notifyMode: "failure-change",
+
+ // A preset that is used as a base for Jest's configuration
+ // preset: undefined,
+
+ // Run tests from one or more projects
+ // projects: undefined,
+
+ // Use this configuration option to add custom reporters to Jest
+ // reporters: undefined,
+
+ // Automatically reset mock state before every test
+ // resetMocks: false,
+
+ // Reset the module registry before running each individual test
+ // resetModules: false,
+
+ // A path to a custom resolver
+ // resolver: undefined,
+
+ // Automatically restore mock state and implementation before every test
+ // restoreMocks: false,
+
+ // The root directory that Jest should scan for tests and modules within
+ rootDir: "./js_tests",
+
+ // A list of paths to directories that Jest should use to search for files in
+ // roots: [
+ // ""
+ // ],
+
+ // Allows you to use a custom runner instead of Jest's default test runner
+ // runner: "jest-runner",
+
+ // The paths to modules that run some code to configure or set up the testing environment before each test
+ // setupFiles: ["/fetch-setup.js"],
+
+ // A list of paths to modules that run some code to configure or set up the testing framework before each test
+ // setupFilesAfterEnv: [],
+
+ // The number of seconds after which a test is considered as slow and reported as such in the results.
+ // slowTestThreshold: 5,
+
+ // A list of paths to snapshot serializer modules Jest should use for snapshot testing
+ // snapshotSerializers: [],
+
+ // The test environment that will be used for testing
+ testEnvironment: "jsdom",
+
+ // Options that will be passed to the testEnvironment
+ // testEnvironmentOptions: {},
+
+ // Adds a location field to test results
+ // testLocationInResults: false,
+
+ // The glob patterns Jest uses to detect test files
+ testMatch: [
+ "**/__tests__/**/*.[jt]s?(x)",
+ "**/?(*.)+(spec|test).[tj]s?(x)"
+ ],
+
+ // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
+ // testPathIgnorePatterns: [
+ // "/node_modules/"
+ // ],
+
+ // The regexp pattern or array of patterns that Jest uses to detect test files
+ // testRegex: [],
+
+ // This option allows the use of a custom results processor
+ // testResultsProcessor: undefined,
+
+ // This option allows use of a custom test runner
+ // testRunner: "jest-circus/runner",
+
+ // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
+ // testURL: "http://localhost",
+
+ // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
+ // timers: "real",
+
+ // A map from regular expressions to paths to transformers
+ // transform: undefined,
+
+ // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
+ // transformIgnorePatterns: [
+ // "/node_modules/",
+ // "\\.pnp\\.[^\\/]+$"
+ // ],
+
+ // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
+ // unmockedModulePathPatterns: undefined,
+
+ // Indicates whether each individual test should be reported during the run
+ verbose: false,
+
+ // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
+ // watchPathIgnorePatterns: [],
+
+ // Whether to use watchman for file crawling
+ // watchman: true,
+};
diff --git a/js_tests/fetch-setup.js b/js_tests/fetch-setup.js
new file mode 100644
index 00000000..c2c3d0dc
--- /dev/null
+++ b/js_tests/fetch-setup.js
@@ -0,0 +1,3 @@
+// require('jest-fetch-mock').enableMocks();
+import fetchMock from 'jest-fetch-mock';
+fetchMock.enableMocks();
diff --git a/js_tests/global-setup.js b/js_tests/global-setup.js
new file mode 100644
index 00000000..8c38370b
--- /dev/null
+++ b/js_tests/global-setup.js
@@ -0,0 +1,14 @@
+const path = require('path');
+
+const { setup: setupDevServer } = require('jest-dev-server');
+
+const server_path = path.resolve(__dirname, "serve_static.js");
+
+module.exports = async function globalSetup() {
+ await setupDevServer({
+ command: `node ${server_path}`,
+ launchTimeout: 50000,
+ port: 3000,
+ debug: true
+ });
+};
diff --git a/js_tests/global-teardown.js b/js_tests/global-teardown.js
new file mode 100644
index 00000000..094a8349
--- /dev/null
+++ b/js_tests/global-teardown.js
@@ -0,0 +1,5 @@
+const { teardown: teardownDevServer } = require('jest-dev-server');
+
+module.exports = async function globalTeardown() {
+ await teardownDevServer();
+};
diff --git a/js_tests/serve_static.js b/js_tests/serve_static.js
new file mode 100644
index 00000000..47e6d236
--- /dev/null
+++ b/js_tests/serve_static.js
@@ -0,0 +1,16 @@
+const path = require("path");
+const express = require("express");
+const app = express();
+const port = 3000;
+
+const PRJ_PATH = path.resolve(
+ __dirname, '..', 'django_comments_xtd', 'static', 'django_comments_xtd'
+);
+
+app.use(express.static(PRJ_PATH));
+
+app.get('/', (req, res) => {
+ res.send("Serve static resources for jest tests.");
+});
+
+app.listen(port, () => {});
diff --git a/js_tests/tests/scene1/README.md b/js_tests/tests/scene1/README.md
new file mode 100644
index 00000000..3b829c25
--- /dev/null
+++ b/js_tests/tests/scene1/README.md
@@ -0,0 +1,8 @@
+# JavaScript Tests - Scene 1
+
+This scene represents the situation in which:
+ * there is no comments posted yet,
+ * only a comment form is displayed.
+ * Therefore the reactions.js module is not used, and
+ * neither is used the reply_forms.js module.
+ * Only the module comment_form.js is tested.
diff --git a/js_tests/tests/scene1/comment_form.test.js b/js_tests/tests/scene1/comment_form.test.js
new file mode 100644
index 00000000..05d49f8f
--- /dev/null
+++ b/js_tests/tests/scene1/comment_form.test.js
@@ -0,0 +1,379 @@
+import fs from 'fs';
+import path from 'path';
+
+import {
+ findByText, fireEvent, getByLabelText, getByPlaceholderText, getByRole,
+ waitFor
+} from '@testing-library/dom';
+import '@testing-library/jest-dom/extend-expect';
+import { JSDOM, ResourceLoader } from 'jsdom';
+
+let dom;
+let container;
+let qs_cform;
+
+const index_html_path = path.resolve(__dirname, './index.html');
+
+const preview_form_wrong_email_200 = fs.readFileSync(
+ path.resolve(__dirname, './preview_form_wrong_email_200.html')
+).toString();
+
+const preview_form_success_200 = fs.readFileSync(
+ path.resolve(__dirname, './preview_form_success_200.html')
+).toString();
+
+const post_form_receives_400 = fs.readFileSync(
+ path.resolve(__dirname, './post_form_receives_400.html')
+).toString();
+
+const post_form_receives_201 = fs.readFileSync(
+ path.resolve(__dirname, './post_form_receives_201.html')
+).toString();
+
+const post_form_receives_202 = fs.readFileSync(
+ path.resolve(__dirname, './post_form_receives_202.html')
+).toString();
+
+function prepare_form_with_wrong_email(formEl) {
+ const comment_ta = getByPlaceholderText(formEl, /your comment/i);
+ fireEvent.change(comment_ta, {target: {value: "This is my comment"}});
+ const name_field = getByLabelText(formEl, /name/i);
+ fireEvent.change(name_field, {target: {value: "Emma"}});
+ const email_field = getByLabelText(formEl, /mail/i);
+ // Feed the email field with a non-valid email address.
+ fireEvent.change(email_field, {target: {value: "emma"}});
+}
+
+function prepare_valid_form(formEl) {
+ const comment_ta = getByPlaceholderText(formEl, /your comment/i);
+ fireEvent.change(comment_ta, {target: {value: "This is my comment"}});
+ const name_field = getByLabelText(formEl, /name/i);
+ fireEvent.change(name_field, {target: {value: "Emma"}});
+ const email_field = getByLabelText(formEl, /mail/i);
+ fireEvent.change(email_field, {target: {value: "emma@example.com"}});
+}
+
+describe("comments.test.js module", () => {
+ beforeEach(async () => {
+ const resourceLoader = new ResourceLoader({
+ proxy: "http://localhost:3000",
+ strictSSL: false
+ });
+ const opts = { runScripts: "dangerously", resources: resourceLoader };
+ dom = await JSDOM.fromFile(index_html_path, opts);
+ await new Promise(resolve => {
+ dom.window.addEventListener("DOMContentLoaded", () => {
+ container = dom.window.document.body;
+ qs_cform = "[data-dcx=comment-form]";
+ resolve();
+ });
+ });
+ });
+
+ it("asserts window.dcx.comment_form attributes", () => {
+ expect(dom.window.dcx !== null && dom.window.dcx !== undefined);
+ expect(dom.window.dcx.comment_form !== null);
+ expect(dom.window.dcx.comment_form.formWrapper === qs_cform);
+
+ const elem = container.querySelector(qs_cform);
+ expect(dom.window.dcx.comment_form.formWrapperEl === elem);
+
+ const form = elem.querySelector("form");
+ expect(dom.window.dcx.comment_form.formEl === form);
+ });
+
+ it("previewing empty form focuses on textarea comment", () => {
+ const cFormWrapper = container.querySelector(qs_cform);
+ const preview = getByRole(cFormWrapper, "button", {name: /preview/i});
+ fireEvent.click(preview);
+ const comment_ta = getByPlaceholderText(cFormWrapper, /your comment/i);
+ expect(dom.window.document.activeElement).toEqual(comment_ta);
+ });
+
+ it("previewing form focuses on input name", () => {
+ // This happens only when the comment textarea has content.
+ const cFormWrapper = container.querySelector(qs_cform);
+ const comment_ta = getByPlaceholderText(cFormWrapper, /your comment/i);
+ fireEvent.change(comment_ta, {target: {value: "This is my comment"}});
+ const preview = getByRole(cFormWrapper, "button", {name: /preview/i});
+ fireEvent.click(preview);
+ const name_field = getByLabelText(cFormWrapper, /name/i);
+ expect(dom.window.document.activeElement).toEqual(name_field);
+ });
+
+ it("previewing form focuses on input email", () => {
+ // This happens only when both comment and name fields have content.
+ const cFormWrapper = container.querySelector(qs_cform);
+ const comment_ta = getByPlaceholderText(cFormWrapper, /your comment/i);
+ fireEvent.change(comment_ta, {target: {value: "This is my comment"}});
+ const name_field = getByLabelText(cFormWrapper, /name/i);
+ fireEvent.change(name_field, {target: {value: "Emma"}});
+ const preview = getByRole(cFormWrapper, "button", {name: /preview/i});
+ fireEvent.click(preview);
+ const email_field = getByLabelText(cFormWrapper, /mail/i);
+ expect(dom.window.document.activeElement).toEqual(email_field);
+ });
+
+ it("preview tampered form receives 400 response", async () => {
+ const cFormWrapper = container.querySelector(qs_cform);
+ const formEl = cFormWrapper.querySelector("form");
+ prepare_form_with_wrong_email(formEl);
+
+ dom.window.fetch = jest.fn(() => Promise.resolve({
+ status: 400,
+ json: () => Promise.resolve({
+ html: post_form_receives_400
+ })
+ }));
+
+ const preview = getByRole(formEl, "button", {name: /preview/i});
+ fireEvent.click(preview);
+
+ const formData = new dom.window.FormData(formEl);
+ formData.append("preview", 1);
+
+ expect(dom.window.fetch.mock.calls.length).toEqual(1);
+ expect(dom.window.fetch).toHaveBeenCalledWith(
+ "file:///comments/post/",
+ {
+ method: "POST",
+ headers: {
+ "X-Requested-With": "XMLHttpRequest",
+ },
+ body: formData
+ }
+ );
+
+ await findByText(container, "An error has happened.");
+ await findByText(container, "The comment form failed security verification.");
+ await waitFor(() => {
+ const qs = "[data-dcx=comment-form] form h6";
+ const h6 = dom.window.document.querySelector(qs);
+ expect(h6.textContent.indexOf("An error has happened.") > -1);
+ });
+ dom.window.fetch.mockClear();
+ });
+
+ it("preview form with wrong email receives 200 response", async () => {
+ const cFormWrapper = container.querySelector(qs_cform);
+ const formEl = cFormWrapper.querySelector("form");
+ prepare_form_with_wrong_email(formEl);
+
+ dom.window.fetch = jest.fn(() => Promise.resolve({
+ status: 200,
+ json: () => Promise.resolve({
+ html: preview_form_wrong_email_200,
+ field_focus: "email"
+ })
+ }));
+
+ const preview = getByRole(formEl, "button", {name: /preview/i});
+ fireEvent.click(preview);
+
+ const formData = new dom.window.FormData(formEl);
+ formData.append("preview", 1);
+
+ expect(dom.window.fetch.mock.calls.length).toEqual(1);
+ expect(dom.window.fetch).toHaveBeenCalledWith(
+ "file:///comments/post/",
+ {
+ method: "POST",
+ headers: {
+ "X-Requested-With": "XMLHttpRequest",
+ },
+ body: formData
+ }
+ );
+
+ await findByText(container, "Enter a valid email address.");
+ const email_input = container.querySelector("form [name=email]");
+ expect(dom.window.document.activeElement).toEqual(email_input);
+ dom.window.fetch.mockClear();
+ });
+
+ it("preview form receives 200 response", async () => {
+ const cFormWrapper = container.querySelector(qs_cform);
+ const formEl = cFormWrapper.querySelector("form");
+ prepare_valid_form(formEl);
+
+ dom.window.fetch = jest.fn(() => Promise.resolve({
+ status: 200,
+ json: () => Promise.resolve({ html: preview_form_success_200 })
+ }));
+
+ const preview = getByRole(formEl, "button", {name: /preview/i});
+ fireEvent.click(preview);
+
+ const formData = new dom.window.FormData(formEl);
+ formData.append("preview", 1);
+
+ expect(dom.window.fetch.mock.calls.length).toEqual(1);
+ expect(dom.window.fetch).toHaveBeenCalledWith(
+ "file:///comments/post/",
+ {
+ method: "POST",
+ headers: {
+ "X-Requested-With": "XMLHttpRequest",
+ },
+ body: formData
+ }
+ );
+
+ await waitFor(() => {
+ expect(
+ dom.window.document.querySelector("[data-dcx=preview]")
+ ).toBeInTheDocument();
+ });
+ dom.window.fetch.mockClear();
+ });
+
+ it("post form receives 400 response", async () => {
+ const cFormWrapper = container.querySelector(qs_cform);
+ const formEl = cFormWrapper.querySelector("form");
+ prepare_valid_form(formEl);
+
+ dom.window.fetch = jest.fn(() => Promise.resolve({
+ status: 400,
+ json: () => Promise.resolve({ html: post_form_receives_400 })
+ }));
+
+ const send_btn = getByRole(formEl, "button", {name: /send/i});
+ fireEvent.click(send_btn);
+
+ const formData = new dom.window.FormData(formEl);
+ formData.append("post", 1);
+
+ expect(dom.window.fetch.mock.calls.length).toEqual(1);
+ expect(dom.window.fetch).toHaveBeenCalledWith(
+ "file:///comments/post/",
+ {
+ method: "POST",
+ headers: {
+ "X-Requested-With": "XMLHttpRequest"
+ },
+ body: formData
+ }
+ );
+
+ await findByText(container, "An error has happened.");
+ await findByText(container, "The comment form failed security verification.");
+ await waitFor(() => {
+ const qs = "[data-dcx=comment-form] form h6";
+ const h6 = dom.window.document.querySelector(qs);
+ expect(h6.textContent.indexOf("An error has happened.") > -1);
+ });
+ dom.window.fetch.mockClear();
+ });
+
+ it("post form receives 201 response", async () => {
+ const cFormWrapper = container.querySelector(qs_cform);
+ const formEl = cFormWrapper.querySelector("form");
+ prepare_valid_form(formEl);
+
+ dom.window.fetch = jest.fn(() => Promise.resolve({
+ status: 201,
+ json: () => Promise.resolve({ html: post_form_receives_201 })
+ }));
+
+ const send_btn = getByRole(formEl, "button", {name: /send/i});
+ fireEvent.click(send_btn);
+
+ const formData = new dom.window.FormData(formEl);
+ formData.append("post", 1);
+
+ expect(dom.window.fetch.mock.calls.length).toEqual(1);
+ expect(dom.window.fetch).toHaveBeenCalledWith(
+ "file:///comments/post/",
+ {
+ method: "POST",
+ headers: {
+ "X-Requested-With": "XMLHttpRequest"
+ },
+ body: formData
+ }
+ );
+
+ await findByText(container, "Comment published");
+ await waitFor(() => {
+ const qs = "[data-dcx=comment-form] form > div > div";
+ const alert = dom.window.document.querySelector(qs);
+ expect(alert.textContent.indexOf("Comment published") > -1);
+ });
+ dom.window.fetch.mockClear();
+ });
+
+ it("post form receives 202 response", async () => {
+ const cFormWrapper = container.querySelector(qs_cform);
+ const formEl = cFormWrapper.querySelector("form");
+ prepare_valid_form(formEl);
+
+ dom.window.fetch = jest.fn(() => Promise.resolve({
+ status: 202,
+ json: () => Promise.resolve({ html: post_form_receives_202 })
+ }));
+
+ const send_btn = getByRole(formEl, "button", {name: /send/i});
+ fireEvent.click(send_btn);
+
+ const formData = new dom.window.FormData(formEl);
+ formData.append("post", 1);
+
+ expect(dom.window.fetch.mock.calls.length).toEqual(1);
+ expect(dom.window.fetch).toHaveBeenCalledWith(
+ "file:///comments/post/",
+ {
+ method: "POST",
+ headers: {
+ "X-Requested-With": "XMLHttpRequest"
+ },
+ body: formData
+ }
+ );
+
+ const text = "Comment confirmation requested";
+ await findByText(container, text);
+ await waitFor(() => {
+ const qs = "[data-dcx=comment-form] form > div > div";
+ const alert = dom.window.document.querySelector(qs);
+ expect(alert.textContent.indexOf(text) > -1);
+ });
+ dom.window.fetch.mockClear();
+ });
+
+ it("post form receives 500 response", async () => {
+ const cFormWrapper = container.querySelector(qs_cform);
+ const formEl = cFormWrapper.querySelector("form");
+ prepare_valid_form(formEl);
+
+ dom.window.fetch = jest.fn(() => Promise.resolve({
+ status: 500,
+ json: () => Promise.resolve({})
+ }));
+
+ const alertMock = jest.spyOn(dom.window, 'alert').mockImplementation();
+
+ const send_btn = getByRole(formEl, "button", {name: /send/i});
+ fireEvent.click(send_btn);
+
+ const formData = new dom.window.FormData(formEl);
+ formData.append("post", 1);
+
+ expect(dom.window.fetch.mock.calls.length).toEqual(1);
+ expect(dom.window.fetch).toHaveBeenCalledWith(
+ "file:///comments/post/",
+ {
+ method: "POST",
+ headers: {
+ "X-Requested-With": "XMLHttpRequest"
+ },
+ body: formData
+ }
+ );
+
+ await waitFor(() => {
+ expect(alertMock).toHaveBeenCalledTimes(1);
+ });
+ dom.window.fetch.mockClear();
+ alertMock.mockClear();
+ });
+});
diff --git a/js_tests/tests/scene1/comments.test.js b/js_tests/tests/scene1/comments.test.js
new file mode 100644
index 00000000..61102948
--- /dev/null
+++ b/js_tests/tests/scene1/comments.test.js
@@ -0,0 +1,46 @@
+import path from 'path';
+
+import { getByText } from '@testing-library/dom';
+import '@testing-library/jest-dom/extend-expect';
+import { JSDOM, ResourceLoader } from 'jsdom';
+
+
+const html_path = path.resolve(__dirname, './index.html');
+
+let dom;
+let container;
+let qs_cform;
+
+describe("comments.test.js module", () => {
+ beforeEach(async () => {
+ const resourceLoader = new ResourceLoader({
+ proxy: "http://localhost:3000",
+ strictSSL: false
+ });
+ const opts = { runScripts: "dangerously", resources: resourceLoader };
+ dom = await JSDOM.fromFile(html_path, opts);
+ await new Promise(resolve => {
+ dom.window.addEventListener("DOMContentLoaded", () => {
+ dom.window.dcx.init_comments();
+ container = dom.window.document.body;
+ qs_cform = "[data-dcx=comment-form]";
+ resolve();
+ });
+ });
+ });
+
+ it("creates window.dcx.comment_form attribute !== null", () => {
+ expect(dom.window.dcx !== null && dom.window.dcx !== undefined);
+ expect(dom.window.dcx.comment_form !== null);
+ });
+
+ it("has a div with [data-dcx=comment-form]", () => {
+ expect(container.querySelector(qs_cform));
+ expect(getByText(container, 'Post your comment')).toBeInTheDocument();
+ });
+
+ it("creates window.dcx.reply_forms_handler attribute === null", () => {
+ expect(dom.window.dcx !== null && dom.window.dcx !== undefined);
+ expect(dom.window.dcx.comment_form === null);
+ });
+});
diff --git a/js_tests/tests/scene1/index.html b/js_tests/tests/scene1/index.html
new file mode 100644
index 00000000..24c84d60
--- /dev/null
+++ b/js_tests/tests/scene1/index.html
@@ -0,0 +1,148 @@
+
+
+
+
+
+ dcx-demo • stories
+
+
+
+
+
+
+
The battle over the future of the Internet is a power grab that pits well-heeled lobbyists, corrupt legislators, phony front groups and the world’s most powerful telecommunications companies against the rest of us — the millions of Americans who use the Internet every day, in increasingly inventive ways.
+
Policymakers are public officials, and it’s their job to serve the public interest. You can play an important role by helping spread the word about Net Neutrality, meeting face to face with elected officials and urging them to protect the open Internet.
+
You can start by urging the Senate to stand up for Net Neutrality.
{% trans "New comments are not allowed." %}
{% block extra_js %} - - +