Testing in JavaScript and WordPress Coding Standards (WPCS)

Summary: Learning about testing in JavaScript, Understanding importance of WordPress Coding Standards, PHP and JavaScript Coding Standards for WordPress.

Jest

Jest is a powerful library for testing JavaScript code, maintained by Facebook. It’s especially suited for testing React applications but can be used to test any JavaScript code. Jest is fast, easy to use, and offers features like snapshot testing and built-in matchers.

yarn add --dev jest
# or
npm install --save-dev jest

Example

const sum = (a, b) => a + b;
const mul = (a, b) => a * b;
const sub = (a, b) => a - b;
const div = (a, b) => a / b;

module.exports = { sum, mul, sub, div };
const { sum, mul, sub, div } = require('./math');

test('Adding 1 + 1 equals 2', () => {
  expect(sum(1, 1)).toBe(2);
});
test('Multiplying 1 * 1 equals 1', () => {
  expect(mul(1, 1)).toBe(1);
});
test('Subtracting 1 - 1 equals 0', () => {
  expect(sub(1, 1)).toBe(0);
});
test('Dividing 1 / 1 equals 1', () => {
  expect(div(1, 1)).toBe(1);
});

Matchers

Jest provides various matchers to test values:

  • toBe() for strict equality
  • toEqual() for deep equality
  • toBeNull(), toBeDefined(), toBeUndefined(), toBeTruthy(), toBeFalsy()
  • Comparison matchers: toBeGreaterThan(), toBeLessThan(), etc.
  • toMatch() for regex pattern matching
  • toContain() for arrays
  • toHaveLength(), toHaveProperty(), toThrow(), toBeInstanceOf()

Setup and Teardown

Use beforeAll(), beforeEach(), afterAll(), and afterEach() to run setup and teardown code.

Mocking

Mocking allows you to isolate your tests from external dependencies. Jest provides various utilities for mocking functions and modules:

  • spyOn(): Spy on functions without modifying their implementation.
  • jest.fn(): Create mock functions.
  • mocks directory: Mock entire modules.

JavaScript Lint

ESLint

ESLint statically analyzes your code to quickly find problems. It is built into most text editors and you can run ESLint as part of your continuous integration pipeline.

JSLint

It is the oldest of the four and was created by Douglas Crockford in 2002 to enforce the good parts of JavaScript. Unlike ESLint, JSLint is not configurable.

JSHint

It is the configurable version of JSLint and has basic ES6 support. But the downsides of using JSHint are that it is difficult to know which rule is causing an error and it has no custom rule support.

JSCS

It is a code style checker. It only catches issues related to code formatting, and not potential bugs or errors.

WordPress Coding Standards

The purpose of the WordPress Coding Standards is to create a baseline for collaboration and review within various aspects of the WordPress open source project and community, from core code to themes to plugins.

Why have coding standards?

Coding standards help avoid common coding errors, improve the readability of code, and simplify modification. They ensure that files within the project appear as if they were created by a single person.

Following the standards means anyone will be able to understand a section of code and modify it, if needed, without regard to when it was written or by whom.

PHP Coding Standards For WordPress

1. PHP Tags:

  • Multiline PHP: PHP open and close tags must be on their own lines.
  • Single Line PHP: Inline PHP can be embedded within HTML tags.
  • No Shorthand Tags: Always use full PHP tags <?php ... ?>, not <? ... ?> or <?= ... ?>.

2. Quotes:

  • Single Quotes: Use for simple strings.
  • Double Quotes: Use when including variables or escape sequences.

3. Include/Require Statements:

  • No Parentheses: Do not use parentheses with include or require.
  • Prefer Require: Use require[_once] for critical files to ensure execution stops if the file is missing.

4. Naming Conventions:

  • Variables/Functions: Use lowercase letters and underscores.
  • Classes/Interfaces: Capitalize words, separate with underscores.
  • Constants: Uppercase letters, separated by underscores.

5. Whitespace and Indentation:

  • Spaces: Use spaces around operators and after commas.
  • Tabs: Use tabs for indentation, not spaces.
  • Trailing Spaces: Remove trailing whitespace at the end of lines and functions.

6. Brace Style:

  • All Blocks: Always use braces {} even for single-line statements.

7. Arrays:

  • Long Syntax: Use array() instead of [].

8. Multiline Function Calls:

  • Parameters: Each parameter should be on a separate line.

9. Type Declarations:

  • Spacing: One space before and after type declarations.

10. Namespace and Import Statements:

  • Namespaces: Capitalized words separated by underscores.
  • Use Statements: Organized and placed at the top of files.

11. Spread Operator:

  • Spacing: One space before, no spaces after the spread operator.

JavaScript Coding Standards For WordPress

  • Indentation with tabs.
  • No whitespace at the end of line or on blank lines.
  • Lines should usually be no longer than 80 characters, and should not exceed 100 (counting tabs as 4 spaces). This is a “soft” rule, but long lines generally indicate unreadable or disorganized code.
  • if/else/for/while/try blocks should always use braces, and always go on multiple lines.
  • Unary special-character operators (e.g., ++--) must not have space next to their operand.
  • Any , and ; must not have preceding space.
  • Any ; used as a statement terminator must be at the end of the line.
  • Any : after a property name in an object definition must not have preceding space.
  • The ? and : in a ternary conditional must have space on both sides.
  • No filler spaces in empty constructs (e.g., {}[]fn()).
  • There should be a new line at the end of each file.
  • Any ! negation operator should have a following space.*
  • All function bodies are indented by one tab, even if the entire file is wrapped in a closure.*
  • Spaces may align code within documentation blocks or within a line, but only tabs should be used at the start of a line.*

    «
    »

    Leave a Reply

    Your email address will not be published. Required fields are marked *