Code Monkey home page Code Monkey logo

eventsourcemock's Introduction

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.

eventsourcemock's People

Contributors

ahomu avatar gcedo avatar tamlyn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

eventsourcemock's Issues

Error with EventSource undefined

Hello, I have created an EventSource in a file configJSDom.js:

import EventSource from 'eventsourcemock';

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

It was used by jest and in my test I add import { sources } from 'eventsourcemock'; and try to mock that:
new EventSource(Utils.apiUrl()+"/sse_stream", { withCredentials: true });

With that:

sources[Utils.apiUrl()+"/sse_stream"].emitOpen();
  sources['http://example.com/events'].emit(
    messageEvent.type,
    messageEvent
  );

But it crash with that:

    TypeError: Cannot read property 'emitOpen' of undefined

      138 |   tree.instance().startEvent();
      139 |   expect(cookie.get("sse_loading")).toBe("true");
    > 140 |   sources[Utils.apiUrl()+"/sse_stream"].emitOpen();
          |                                         ^
      141 |   sources['http://example.com/events'].emit(
      142 |     messageEvent.type,
      143 |     messageEvent

      at Object.emitOpen (src/__test__/Panel.test.js:140:41)

Have I forgot something ?

What is the latest version?

Hello!

I noticed NPM registry has more versions for this package than the tags available here on GitHub. Was that intended?

The result of running npm info eventsourcemock time is

{
  modified: '2018-04-29T20:34:16.111Z',
  created: '2017-06-09T12:21:21.619Z',
  '1.0.0': '2017-06-09T12:21:21.619Z',
  '1.0.1': '2017-06-09T13:58:48.377Z',
  '1.1.0': '2018-01-07T18:52:56.546Z',
  '2.0.0': '2018-04-29T20:34:12.778Z'
}

Also, since the latest version bump was a major, is there any changelog I can check for the changes?

Thank you!

Setup docs

Compared to the current docs, when one creates a React app with the now standard npm create-react-app, the way to integrate this library will rather be in src/setupTests.js :

// src/setupTests.js
import EventSource from "eventsourcemock";

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.