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-test

v0.7.11

Published

Run single test, or event chain of async/sync tests and retry each if needed

Downloads

12

Readme

Als-test

Small package for testing on backend. Run single test, or event chain of asynchronous/synchronous tests and retry each if needed.

Updates

Action functions

Actions functions getting expected value and result value and return boolean: true or false. You can write your own action functions.

Syntax for action function:

actionName(expected:primitive,result:primitive):boolean

Here are existing functions:

equal(expected,result)
notEqual(expected,result)
includes(expected,result)
notIncludes(expected,result)
greater(expected,result)
smaller(expected,result)
$greater(expected,result)
$smaller(expected,result)

Type of parameters, have to be primitive (string,number,bigint,boolean,undfined,symbol,null).

Example:

let Test = require('als-test')
let {equal,notEqual,includes,greater,smaller} = Test

equal(2,4) // false | expected == result
notEqual(2,4) // true | expected !== result
icludes('Alex','name Alex') // true | expected.includes(result)
greater(4,3) // true | expected > result
smaller(4,3) // false | expected < result
$greater(4,4) // true | expected >= result
$smaller(4,4) // true | expected <= result

Syntax

Test class get array of tests and run it one after another. If function async, or retrying, it will wait till job is done.

Syntax:

let Test = require('als-test')
let {equal,notEqual,includes,greater,smaller} = Test // actions
let {mesureTime,buildTime,isFn,isAsync,outcome} = Test // methods

Test.fullError:boolean // true by default. If false, on error, only error msg appear.

let someTest = new Test(title:string,[
   {
   // title for test
      title:string,

   // can be primitive or async/sync function which return expected 
      expected:primitive|Function|undefined|null, value

   // can be primitive or async/sync function which return result value
   // If result return new Error('your msg') test will return error
      result:primitive|Function|undefined|null|instanceof Error, 

   // action function from actions (equal,notEqual,includes,greater,smaller), or your own one
      action:Function,

   // how many times to retry if test fail
      times:number,
      
   // interval in ms between retries. default:1000
      interval:number,
   
   // Number of ms. Waiting before executing result function
      wait:number 
   },
])

someTest.run(vars={}): Promise
Test.mesureTime(fn) // return function(vars)/async function(vars) which return time in ms
Test.buildTime(ms) // parse 'minuts seconds miliseconds'' from miliseconds
Test.isFn(param) // checks if param is a function
Test.isAsync(param) // checks if param is async function
Test.outcome() // return objects with results of tests

Result and expected function binded test object. Therefore, this inside those functions (if it's not arrow function) applies to test object. Each test has empty object test.vars for case to store variables and methods and use them inside tests.

run method gets also vars and methods, which will included inside this.vars and can be used inside each test with context this.

Math Example

Example:

let Test = require('als-test')
let {equal,includes} = Test

let some = new Test('Math tests',[
   {
      title:'Prepare expected value',
      result:function() {
         this.vars.value = 2
         return 'Value prepared succesfully'
      }
   },
   {
      title:'Compare numbers',
      expected:function({value}) {
         return value
      },
      result:function() {
         return 2
      },
      action:equal
   },
   {
      title:'Compare another numbers',
      expected:2,
      result:function() {
         return 4
      },
      action:Test.equal
   },
   {
      title:'Check if includes',
      expected:'Alex',
      result:function() {return 'Name is Alex'},
      action:includes
   },
   {
      title:'This one will return error',
      expected:'Alex',
      result:function() {return 'Name is Alex'+notDefinedVar},
      action:Test.includes
   },
   {
      title:'This one will throw error',
      expected:'Alex',
      result:function() {return new Error('Error message from result function')},
      action:Test.includes
   }
])

some.run({name:'Alex'})

Result:


Math tests

   ✱  Prepare expected value
      Done:Value prepared succesfully

   ✓  Compare numbers passed.
      Expected: 2, result: 2, action: equal.

   ✘  Compare another numbers failed.
      Expected: 2, result: 4, action: equal.

   ✓  Check if includes passed.
      Expected: Alex, result: Name is Alex, action: includes.

   !  This one will return error.
      error: notDefinedVar is not defined

   !  This one will throw error.
      error: Error message from result function


Report for Math tests
  Passed: 2  Failed: 1  Errors: 2  Done: 1
  

Async example

Example:

let Test = require('als-test')
let {equal,notEqual,includes,greater,smaller} = Test
let fetch = require('als-request')

async function getTodos(){
   let url = 'https://jsonplaceholder.typicode.com/todos'
   const response = await fetch(url,{});
   let data = response.data
   try {data = JSON.parse(data)} catch{}
   return typeof data
}

new Test('Async tests',[
   {
      title:'Fetch todos type of result',
      expected:'object',
      result:getTodos,
      action:equal
   },
   {
      title:'Fetch totos on expected and on result',
      expected:async function() {
         return (await this.getTodos()).length
      },
      result:async function() {
         return (await this.getTodos()).length
      },
      action:equal
   },
   {
      title:'Fetch todos - count todos - failed and retry example',
      result:async function() {
         return (await this.getTodos()).length
      },
      expected:201,
      action:equal,
      times:5,
      interval:500,
   },
   {
      title:'Testing error msg',
      result:async function(){
         const response = await fetch(url,{});
         const result = await response.json();
         return result.length
      },
      expected:200,
      action:equal
   }
]).run({},{getTodos})

Result in console:

Async tests

   ✓  Fetch todos type of result passed.
      Expected: object, result: object, action: equal.

   ✓  Fetch totos on expected and on result passed.
      Expected: 6, result: 6, action: equal.

Try 1: failed
Try 2: failed
Try 3: failed
Try 4: failed
Try 5: failed


   ✘  Fetch todos - count todos - failed and retry example failed.
      Expected: 201, result: 6, action: equal.

   !  Testing error msg.
      error: url is not defined



Report for Async tests
  Passed: 2  Failed: 1  Errors: 1  Done: 1

Concat tests

// test/test.js
let math = require('./math')
let fetch = require('./fetch')
let Test = require('als-test')
let {writeFileSync} = require('fs')

async function test() {
   await fetch.run() // running fetch test
   math.run() // running math test
   await Test.summary() // summary for all tests to console.log
   let {
      all, // json summary for all tests
      passed, // json summary only for passed tests
      failed, // json summary only for failed tests
      errored, // json summary only for errored tests
      notPassed // json summary only for failed and errored tests
   } = Test.outcome()

   let summaryJson = JSON.stringify(notPassed,null,4)
   writeFileSync('summary.json',summaryJson,'utf-8')
}

test()

Test.summary is async function. Use it with await if something comes after.

npm test

Add to your package json and run npm test.

  "scripts": {
    "test": "node test/test"
  },

Terminate next tests

let Test = require('als-test')
let {equal,notEqual,includes,greater,smaller} = Test
let fetch = require('als-request')


let test = new Test('Async tests',[
   {
      title:'Is api return json?',
      result:async function() {
         this.vars.url = 'https://jsonplaceholder.typicode.com/todoskljfhg'
         const {data} = await fetch(this.vars.url,{});
         try {
            data = JSON.parse(data)
            return 'Api checked. All good.'
         } catch {
            this.terminate = true
            return 'Api is not json.'
         }
      },
   },
   {
      title:'Fetch todos',
      expected:200,
      result:async function() {
         const {data} = await fetch(this.vars.url,{});
         data = JSON.parse(data)
         return data.length
      },
      action:equal,
      times:5,
      interval:500,
   },
   {
      title:'Testing error msg',
      result:async function(){
         const response = await fetch(url,{});
         const result = await response.json();
         return result.length
      },
      expected:200,
      action:equal
   }
]).run()

Result:


Async tests

   ✱  Is api return json?
      Done:Api is not json.

Last action has terminated next tests


Report for Async tests
  Passed: 0  Failed: 0  Errors: 0  Done: 1

Test.run

Test.run combine tests to some category.

Syntax:

Test.run(title,tests=[],vars)

Example:

let test1 = {
   {title,expected,result,action},
   {title,expected,result,action},
   {title,expected,result,action},
}
let test2 = {
   {title,expected,result,action},
   {title,expected,result,action},
   {title,expected,result,action},
}

Test.run(
   'Some combined tests',
   [test1,test2],
   {name:'Alex',value:'some'}
)

On example above, all combined tests, get variables inside this.vars.