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

typescript-easymock

v0.0.4

Published

Delightful class mocks for JavaScript and TypeScript.

Downloads

10

Readme

TypeScript - EasyMock

Delightful unit test mocking for TypeScript, inspired by EasyMock.

Motivation

After extensive consideration of existing mocking frameworks for JavaScript and TypeScript, I came to the conclusion that none of them offered the same level of control in an API as expressive as that of easymock, while providing a high level of type safety.

The goals of typescript-easymock are :

  • Full (real!) typescript support in the test suites. That means your mocks are type checked, symbol renaming works from the production code to the test code and vice versa, go-to-definition / find usages works on the mocks too.
  • Automatic mocking. Modern JavaScript uses classes (and modern TypeScript uses interfaces). These are the structural definition of your objects. Using raw jasmine spies often means you need to explicitly re-create a mock following the structural definition of the object you are mocking. With typescript-easymock you just say which type you want to mock and that mock you obtain.
  • Expressive API.

Usage

Intro

A test with easymock is broken down in three phases:

  1. The record phase. During this phase, invocations of methods of the mocked objects are recorded, but they have no effect. Dummy return values are provided and will be returned by the mocks during the replay phase.
  2. The replay phase. This is where you exercise the class under test. When the mocks are invoked, they record the parameters of each call and return the dummy value that was specified in the record phase.
  3. The verify phase. After the test class has been exercised, you should verify that the actual calls matched the expected calls.

This is what it looks like in code:

// The control is a context you use to create mocks and control the current phase
const control = createControl();

// Create a mock for each dependency of the class under test
const dataServiceMock = control.mock(MyDataService);

// The control always starts in record state. This is where we specify the expected behavior
expectCall(dataServiceMock.fetchUserProfile({ id: 3 })).andReturn(Promise.resolve({ name: "John", email: "[email protected]" }));

// Switch to replay mode
control.replay();

const testClass = new UserProfileInformation(dataServiceMock);
const name = await testClass.getUserNameById(3);

// Check that all expected calls actually happened
control.verify();

// You can use regular assertions from your testing framework (jasmine/jest in this example)
expect(name).toBe("John"); 

Real world usage

Setup and teardown

You will generally create the control and the mocks during the setup of your test (beforeEach), and call control.verify() during your test teardown.

For instance, in Jasmine:

describe('UserProfileInformation', () => {
    let control: IMocksControl
    let testClass: UserProfileInformation
    let dataServiceMock: MyDataService

    beforeEach(() => {
        control = createControl()
        dataServiceMock = control.mock(MyDataService)
        testClass = new UserProfileInformation(dataServiceMock)
    })

    afterEach(() => {
        control.verify();
    })
})

⚠️ Warning: Always avoid side effects in class constructors. If the constructor makes a call to dataServiceMock (and remember that we are still in record mode at this point), then weird things will happen.

Match parameters

typescript-easymock provides a collection of matchers to use when you cannot or don't want to specifiy exactly the parameters which will be passed to a mocked method.

expectCall(dataServiceMock.fetchUserProfile({ id: anyNumber() }))

control.replay()

testClass.getRandomUserName()

Yes, of course in reality you would mock the randomness source used by getRandomUserName such that you can inject a well known value... This is just an example.

Here's another example if you would want to check that the parameter is equal by reference to the expected parameter:

const veryHeavyObject = createSomeVeryComplexObject()
expectCall(queryEngineMock.transform(same(veryHeavyObject)))

control.replay()

// Here, we want to check that the object has been passed as-is and that it was not copied (which would be expensive).
myDatabase.processQuery({ query: veryHeavyObject })