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

ts-passthrough-test-helper

v1.0.2

Published

use the compiler api to test method calls are passed through

Downloads

9

Readme

ts-passthrough-test-helper

npm install --save-dev ts-passthrough-test-helper

Usage

Given types such as the following ( where the types of parameters and return are not important ) :

interface IInterface{
  methodWithReturn(p1: string): boolean;
  voidMethod(): void;

  otherMethod(): void;
}

class PassesThrough implements IInterface {
  constructor(private readonly passedTo: IInterface){}

  methodWithReturn(p1:string){
    return this.passedTo.methodWithReturn(p1);
  }
  voidMethod(){
    this.passedTo.voidMethod();
  }

  otherMethod(){
    // this will be excluded if provide the TypeInfo isValidMethod
  }
}

We want to test that the passedTo constructor argument is indeed used in this manner.

The tsPassThroughHelper testing framework agnostic function provides this functionality. There are jest specific functions too.

How it works

  • Creates an object with mocked methods

    • you determine the class or interface and which methods should passthrough
      • The typeInfo argument
        • path to the source file
        • function that finds the class or interface from the source file
          • This will default to the first type in the source file. Alternatively there is the typeByNameFinder and the more general conditionalTypeFinder.
        • include the methods of your choice with the isValidMethod property ( otherwise all methods are included )
    • you provide the mock for each method
      • The testingFramework argument
        • get for void methods
        • getWithReturn for non void methods - your mock method needs to return the argument
  • Passes you the mock, you return instance of the class that should pass through.

    • The passThrough argument
  • It returns for each method an object with the name of the method and an execute method.

Execution It calls the method on the instance you passed through with the desired number of arguments. Each argument is of the form :

{ arg: number} // where number is the position

Expectation If it is a non void method and you do not return the passthrough return value then it will throw an error. A method will only be deemed to have a return value if it is explicitly typed

  • For all methods it will ask you to expect that the mock method has been called with the expected arguments
    • TestingFramework.expectCalledOnceWithArguments
interface TestingFramework<TMock = any> {
    expectCalledOnceWithArguments: (mock: TMock, args: object[]) => any;

    //implement at least one of these
    get?(): TMock;
    getWithReturn?(returnValue: object): TMock;
}

type ClassOrInterface = ts.ClassDeclaration | ts.InterfaceDeclaration;
type TypeFinder = (sourceFile: ts.SourceFile) => ClassOrInterface;

export interface TypeInfo {
    filePath: string;
    typeFinder?: TypeFinder; // defaults to first class or interface
    isValidMethod?: (methodName: string) => boolean;// defaults to all methods
}

function tsPassThroughHelper(typeInfo: TypeInfo, passThrough: (mock: any) => any, testingFramework: TestingFramework): {
    methodName: string;
    execute(): void;
}[];

Example usage with jest :

function jestPassThroughHelper(
  typeInfo: TypeInfo,
  passThrough: (mock: any) => any
) {
  return tsPassThroughHelper(typeInfo, passThrough, {
    get() {
      return jest.fn();
    },
    getWithReturn(returnValue) {
      return jest.fn().mockReturnValue(returnValue);
    },
    expectCalledOnceWithArguments(mock, args) {
      expect(mock).toHaveBeenCalledWith(...args);
    }
  });
}

function jestPassThroughTestHelper(
  typeInfo: TypeInfo,
  passThrough: (mock: any) => any
) {
  const tests = jestPassThroughHelper(typeInfo, passThrough);
  tests.forEach(t => {
    it(`should passthrough ${t.methodName}`, () => {
      t.execute();
    });
  });
}

describe('passes through', () => {
  jestPassThroughTestHelper(
    {
      filePath: 'path-to-file-only-containing-IInterface',
      isValidMethod(methodName) {
        return methodName !== 'otherMethod';
      }
    },
    mock => {
      return new PassesThrough(mock);
    }
  );
});