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

eventsourcemock

v2.0.0

Published

Mock EventSource in tests.

Downloads

79,873

Readme

eventsourcemock Build Status

A dependency free mock for EventSource objects.

Example (with Jest)

Setup

To setup the mock create a new file where the mock is assigned to the window object.

// __test__/configJSDom.js
import EventSource from 'eventsourcemock';

Object.defineProperty(window, 'EventSource', {
  value: EventSource,
});

Then instruct Jest to use that file during setup in package.json.

"jest": {
  "setupFiles": [
    "./__test__/configJSDom.js"
  ]
}

Usage

Suppose we want to test this component, which updates its state when a message is received from an EventSource instance.

export default class Component extends React.Component {
  props: Props;
  state: State;
  source: $PropertyType<window, 'EventSource'>;

  constructor(props: Props) {
    super(props);
    this.state = {
      counter: 0,
    };
  }

  componentDidMount() {
    this.source = new window.EventSource('http://example.com/events');
    this.source.addEventListener('foo', messageEvent => {
      this.setState({ counter: parseInt(messageEvent.data, 10) });
    });
  }

  componentWillUnmount() {
    this.source.close();
  }

  render() {
    return <div className="Component">{this.state.counter}</div>;
  }
}

We can write a test file that grabs the source from the global sources object and simulates messages:

// @flow
import React from 'react';
import { mount } from 'enzyme';

import Component from './Component';
import { sources } from 'eventsourcemock';

const messageEvent = new MessageEvent('foo', {
  data: '1',
});

describe('update counter on SSE', () => {
  let wrapper;
  beforeAll(() => {
    wrapper = mount(<Component />);
    sources['http://example.com/events'].emitOpen();
  });

  it('should initialise counter to 0', () => {
    expect(wrapper.state('counter')).toBe(0);
  });

  it('should display "0"', () => {
    expect(wrapper.text()).toBe('0');
  });

  it('should update the counter to 1', () => {
    sources['http://example.com/events'].emit(
      messageEvent.type,
      messageEvent
    );
    expect(wrapper.state('counter')).toBe(1);
  });

  it('should close the EventSource on unmount', () => {
    wrapper.unmount();
    expect(sources['http://example.com/events'].readyState).toBe(2);
  });
});

API

sources: { [key: string]: EventSource }

sources holds the EventSource instances created.

import { sources } from 'eventsourcemock';

EventSource

EventSource mocks window.EventSource, providing methods to simulate messages and errors from the network.

import EventSource from 'eventsourcemock';

Constructor

EventSource(
  url: string,
  options?: {
    withCredentials: boolean
  }
)

Properties

__emitter

A reference to the node EventEmitter instance used internally.

onopen

See eventSource.onopen.

onmessage

See eventSource.onmessage.

onerror

See eventSource.onerror.

readyState

See eventSource.readyState.

url

See eventSource.url.

withCredentials

See eventSource.withCredentials.

Methods

emit(eventName: string, messageEvent?: MessageEvent)

Calls each of the listeners registered for the event named eventName, providing messageEvent as argument.

Example

const messageEvent = new MessageEvent('type', {
  data: 'message event data'
});
source.emit(messageEvent.type, messageEvent);

emitOpen()

Simulates the opening of a connection. It sets the ready state to open and invokes the callback.

emitMessage(message: any)

Simulates dispatching of a message, it invokes the onmessage callback.

emitError(error: Error)

Simulates dispatching an error event on the EventSource instance. Causes onerror to be called.

Example (jest)

const onErrorSpy = jest.fn();
const error = new Error('Something went wrong.');
eventSource.onerror = onErrorSpy;
eventSource.emitError(error);
expect(onErrorSpy).toHaveBeenCalledWith(error);
addEventListener(eventName: string, listener: Function)

See EventTarget.addEventListener.

removeEventListener(eventName: string, listener: Function)

See EventTarget.removeEventListener

close()

See EventSource.close.