npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

als-simple-test

v0.4.51

Published

A lightweight test framework (only 170 lines) for JavaScript on browser and nodejs.

Downloads

5

Readme

SimpleTest

SimpleTest is a lightweight JavaScript testing framework (less than 170 lines of code) designed to make it easy to write and run tests for your projects. It offers a simple API and requires minimal setup, making it perfect for small projects or for developers new to testing.

Features

  • Describe test groups with nesting support
  • Run individual tests
  • BeforeEach and AfterEach hooks
  • Asynchronous test support
  • Simple assertion methods
  • Error handling and reporting

Support

The SimpleTest framework relies on JavaScript features that have been widely supported by modern browsers and Node.js for quite some time. However, to provide a more specific answer:

Browsers:

  • Google Chrome: Version 49+
  • Mozilla Firefox: Version 45+
  • Apple Safari: Version 10+
  • Microsoft Edge: Version 14+ (including the Chromium-based Edge)
  • Internet Explorer: Not supported, as the class syntax and some other features are not available in Internet Explorer.

Node.js:

The SimpleTest framework should work on Node.js version 6.x and later. The class syntax and other required features are supported in these versions. However, it is always recommended to use a more recent version of Node.js (e.g., 12.x or newer) for better performance, security, and features.

Please note that using the async/await syntax in your tests will require a minimum Node.js version of 7.6, and for browsers, support is as follows:

  • Google Chrome: Version 55+
  • Mozilla Firefox: Version 52+
  • Apple Safari: Version 10.1+
  • Microsoft Edge: Version 15+ (including the Chromium-based Edge)
  • Using more modern browser versions or Node.js versions is always recommended for the best performance, security, and compatibility with new JavaScript features.

Usage

1. Import SimpleTest

First, import the SimpleTest class into your test file:

For node.js:

const SimpleTest = require('als-simple-test');
let {describe,it,beforeEach,runTests,expect,delay,assert} = SimpleTest

For browser:

<script src="node_modules/als-simple-test/test.js"></script>
<script>
   let {describe,it,beforeEach,runTests,expect,delay,assert} = SimpleTest
</script>

2. Write Tests

Describe blocks

Syntax:

describe(title:string,fn:function,pause:boolean)

Use describe to create a test suite:

describe('My test suite', () => {
  // Your tests go here
});

Nested Describe blocks You can nest describe blocks to organize your tests:

describe('My test suite', () => {
  describe('Subsuite 1', () => {
    // Your tests for subsuite 1
  });

  describe('Subsuite 2', () => {
    // Your tests for subsuite 2
  },true); // pause this test
});

BeforeEach and AfterEach hooks

Use SimpleTest.beforeEach and SimpleTest.afterEach to define hooks that run before and after each test:

describe('My test suite', () => {
  beforeEach(() => {
    // Set up before each test
  });

  afterEach(() => {
    // Clean up after each test
  });

  // Your tests go here
});

BeforeAll and AfterAll hooks

Use SimpleTest.beforeAll and SimpleTest.afterAll to define hooks that run before and after all tests:

describe('My test suite', () => {
  beforeAll(() => {
    // Set up before all tests
  });

  afterAll(() => {
    // Clean up after all tests
  });

  // Your tests go here
});

Writing individual tests

Use SimpleTest.it to write individual tests:

describe('My test suite', () => {
  it('should do something', () => {
    // Your test code
  });

  it('should do something else', () => {
    // Your test code
  });
});

3. Assertions

quick assert

it('should be equal to 2', () => {
  const result = 1 + 1;
  assert(result === 2 ,'Equal to 2')
});

Use SimpleTest.expect to make assertions in your tests:

it('should be equal to 2', () => {
  const result = 1 + 1;
  expect(result).is('Equal to 2').equalTo(2);
});

Assertion Methods

  • equalTo(value): Check if two values are equal
  • between(value1, value2): Check if a value is between two other values
  • below(value): Check if a value is less than another value
  • above(value): Check if a value is above another value
  • atLeast(value): Check if a value is greater than or equal to another value
  • atMost(value): Check if a value is smaller than or equal to another value
  • sameAs(value): Check if two objects are deeply equal
  • defined(): Check if a value is defined
  • matchTo(pattern): Check if a value matches a given regular expression pattern
  • error(): Check if a function throws an error (the function is parameter inside expected)
  • hasProperty(property): Check if an object has a given property
  • includes(value): Checks if expected value includes value
  • instanceof(classType): Checks if expected value is instance of classType
  • closeTo(value2, decimalPlaces = 2): Checks if value2 close to value1 by decimalPlaces

You can use the is and isNot methods with a text parameter to provide a custom description for your test. This text will be displayed in the test output to give you more context about the assertion.

it('should be equal to 2', () => {
  const result = 1 + 1;
  expect(result).is('Equal to 2').equalTo(2);
});

it('should not be equal to 3', () => {
  const result = 1 + 1;
  expect(result).isNot('Equal to 3').equalTo(3);
});

In the examples above, we use is and isNot with a text parameter to describe the expected outcome of the test. The text will be displayed in the console output when running the tests, making it easier to understand the purpose of the assertion.

4. Running Tests

Call SimpleTest.runTests() to run your tests:

SimpleTest.runTests();

Examples Here's an example of a complete test suite using the SimpleTest framework:

const SimpleTest = require('als-simple-test');

describe('Math operations', () => {
  it('should add two numbers', () => {
    const result = 1 + 1;
    expect(result).is('Addition of 1 + 1').equalTo(2)
      });

  describe('Subtraction', () => {
    it('should subtract two numbers', () => {
      const result = 5 - 3;
      expect(result).is('Subtraction of 5 - 3').equalTo(2);
    });

    it('should handle negative results', () => {
      const result = 3 - 5;
      expect(result).is('Negative result').equalTo(-2);
    });
  });

  describe('Multiplication', () => {
    it('should multiply two numbers', () => {
      const result = 2 * 3;
      expect(result).is('Multiplication of 2 * 3').equalTo(6);
    });
  });

  describe('Division', () => {
    it('should divide two numbers', () => {
      const result = 6 / 2;
      expect(result).is('Division of 6 / 2').equalTo(3);
    });

    it('should handle division by zero', () => {
      const result = () => 6 / 0;
      expect(result).is('Division by zero').error();
    });
  });
});

SimpleTest.runTests();

This example demonstrates the usage of nested describe blocks, various assertion methods, and running tests with SimpleTest.runTests().

Using Async it in SimpleTest

In the following example, we demonstrate how to use async it for testing asynchronous functions.

describe('Async Example', () => {
  it('should return a promise that resolves to the sum of two numbers', async () => {
    const asyncAdd = (a, b) => {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(a + b);
        }, 100);
      });
    };

    const result = await asyncAdd(2, 3);
    expect(result).is('Async addition of 2 + 3').equalTo(5);
  });
});

runTests();

Using SimpleTest's delay Method in Async Tests

The SimpleTest framework provides a utility method called delay that creates a Promise that resolves after a specified number of milliseconds. You can use this method to simulate asynchronous behavior in your tests instead of using setTimeout or other asynchronous functions directly.

In the following example, we demonstrate how to use SimpleTest's delay method for testing asynchronous functions.

describe('Async Example with delay', () => {
  it('should return a promise that resolves to the sum of two numbers', async () => {
    const asyncAdd = async (a, b) => {
      await SimpleTest.delay(100);
      return a + b;
    };

    const result = await asyncAdd(2, 3);
    expect(result).is('Async addition of 2 + 3').equalTo(5);
  });
});

SimpleTest.runTests();

In this example, we have an asynchronous function asyncAdd that uses the delay method from SimpleTest to simulate a 100ms delay before returning the sum of two numbers. We use the async keyword with it to define the test function and the await keyword inside the test function to wait for the resolution of the asyncAdd function before asserting the result.

Results

After running tests, the test results can be found in the SimpleTest.results object.

await runTests()
console.log(SimpleTest.results)
console.log(SimpleTest.failed) // array of failed tests titles

Example result structure:

{
  'Rebuild method checking': {
    'should update the mapKeys after modifying $vars': [
      {
        result: true, // true if success, false if failed
        title: 'Check if mapKeys is updated',
        error: null // if no error
      }
    ]
  }
}

Show full error

SimpleTest catching errors and console.log them. You can output only message by setting SimpleTest.showFullError=false.

Additional instruments

async measureTime(fn)

measureTime measures time with performance and return result and execution time for this result.

const {measureTime} = SimpleTest
const pretty = true // return as formated time
const [result,time] = await measureTime(async () => {},pretty)

msToTime(ms)

const {msToTime} = SimpleTest
msToTime(217284.35468) // 3:37.284

formatBytes(bytes,dm=2)

dm - amount of decimals

const {formatBytes} = SimpleTest

formatBytes(217284) // 212.19 KB