All Projects → trurl-master → jsdom-testing-mocks

trurl-master / jsdom-testing-mocks

Licence: MIT license
A set of tools for emulating browser behavior in jsdom environment

Programming Languages

typescript
32286 projects
HTML
75241 projects

Projects that are alternatives of or similar to jsdom-testing-mocks

React Intersection Observer
React implementation of the Intersection Observer API to tell you when an element enters or leaves the viewport.
Stars: ✭ 2,689 (+7167.57%)
Mutual labels:  viewport, intersectionobserver
svelte-inview
A Svelte action that monitors an element enters or leaves the viewport.🔥
Stars: ✭ 358 (+867.57%)
Mutual labels:  viewport, intersectionobserver
react-context-responsive
A package that provides a responsive context to your application, using React Context API.
Stars: ✭ 25 (-32.43%)
Mutual labels:  viewport, matchmedia
Jest Dom
🦉 Custom jest matchers to test the state of the DOM
Stars: ✭ 2,908 (+7759.46%)
Mutual labels:  jsdom, react-testing-library
nextjs-complete-boilerplate
Next js 12.3.1 boilerplate with Styled Components, Jest, React Testing Library, Prettier, ESLint, Plop JS and more 🚀
Stars: ✭ 50 (+35.14%)
Mutual labels:  react-testing-library
progressive-image-loading
A live example of progressive image loading strategies
Stars: ✭ 49 (+32.43%)
Mutual labels:  intersectionobserver
Coherence
Blender viewport renderer using the Unity Engine
Stars: ✭ 28 (-24.32%)
Mutual labels:  viewport
minimal-hapi-react-webpack
Minimal Hapi + React + Webpack + HMR (hot module reloading) Sandbox
Stars: ✭ 55 (+48.65%)
Mutual labels:  jsdom
test-tools
Improves PHPUnit testing productivity by adding a service container and self-initializing fakes
Stars: ✭ 25 (-32.43%)
Mutual labels:  mocks
umock-c
A pure C mocking library
Stars: ✭ 29 (-21.62%)
Mutual labels:  mocks
wp-quicklink
The WordPress plugin for quicklink. ⚡️ Faster subsequent page-loads by prefetching in-viewport links during idle time.
Stars: ✭ 61 (+64.86%)
Mutual labels:  viewport
better-redux-tests
Source code for my article "A better approach for testing your Redux code"
Stars: ✭ 12 (-67.57%)
Mutual labels:  mocks
Mockaco
🐵 HTTP mock server, useful to stub services and simulate dynamic API responses, leveraging ASP.NET Core features, built-in fake data generation and pure C# scripting
Stars: ✭ 213 (+475.68%)
Mutual labels:  mocks
react-simple-boilerplate
Simple React Boilerplate with Webpack, Github Actions, Scss, Lazy Loading etc....
Stars: ✭ 38 (+2.7%)
Mutual labels:  react-testing-library
react-matchmedia-connect
Higher order components for matchMedia
Stars: ✭ 49 (+32.43%)
Mutual labels:  matchmedia
DuBLF DuBlast
Quick Playblast tool for Blender
Stars: ✭ 18 (-51.35%)
Mutual labels:  viewport
vue-in-viewport-mixin
Vue 2 mixin to determine when a DOM element is visible in the client window
Stars: ✭ 99 (+167.57%)
Mutual labels:  viewport
framer-motion-hooks
Fill the hook gap in Framer Motion
Stars: ✭ 160 (+332.43%)
Mutual labels:  viewport
html2md
helloworld 开发者社区开源的一个轻量级,强大的 html 一键转 md 工具,支持多平台文章一键转换,并保存下载到本地。
Stars: ✭ 332 (+797.3%)
Mutual labels:  jsdom
jsdom-devtools-formatter
Make jsdom elements look like real DOM elements in Chrome Devtools console
Stars: ✭ 40 (+8.11%)
Mutual labels:  jsdom

jsdom-testing-mocks

A set of tools for emulating browser behavior in jsdom environment

Build status version PRs Welcome downloads MIT License Code of Conduct

GitHub Repo stars Twitter URL

Installation

npm install --save-dev jsdom-testing-mocks

or

yarn add -D jsdom-testing-mocks

Mock viewport

Mocks matchMedia, allows testing of component's behavior depending on the viewport description (supports all of the Media Features). mockViewport must be called before rendering the component

Example, using React Testing Library:

import { mockViewport } from 'jsdom-testing-mocks';

it('shows the right lines on desktop and mobile', () => {
  const viewport = mockViewport({ width: '320px', height: '568px' });

  render(<TestComponent />);

  expect(
    screen.getByText('Content visible only on small screens')
  ).toBeInTheDocument();

  expect(
    screen.queryByText('Content visible only on large screens')
  ).not.toBeInTheDocument();

  act(() => {
    viewport.set({ width: '1440px', height: '900px' });
  });

  expect(
    screen.queryByText('Content visible only on small screens')
  ).not.toBeInTheDocument();

  expect(
    screen.getByText('Content visible only on large screens')
  ).toBeInTheDocument();

  viewport.cleanup();
});

Also, you can mock the viewport for a group of tests, using mockViewportForTestGroup:

import { mockViewportForTestGroup } from 'jsdom-testing-mocks'

describe('Desktop specific tests', () => {
  mockViewportForTestGroup({ width: '1440px', height: '900px' })

  test('this', () = {
    // ...
  })

  test('that', () = {
    // ...
  })
})

Mock IntersectionObserver

Provides a way of triggering intersection observer events

Example, using React Testing Library:

import { mockIntersectionObserver } from 'jsdom-testing-mocks';

const io = mockIntersectionObserver();

/*
Assuming html:
<div data-testid="container">
  <img src="..." alt="alt text" />
</div>

And an IntersectionObserver, observing the container
*/
it('loads the image when the component is in the viewport', () => {
  const { container } = render(<TestComponent />);

  expect(screen.queryByAltText('alt text')).not.toBeInTheDocument();

  // when the component's observed node is in the viewport - show the image
  act(() => {
    io.enterNode(screen.getByTestId('container'));
  });

  expect(screen.getByAltText('alt text')).toBeInTheDocument();
});

API

mockIntersectionObserver returns an object, that has several useful methods:

.enterNode(node, desc)

Triggers all IntersectionObservers observing the node, with isIntersected set to true and intersectionRatio set to 1. Other IntersectionObserverEntry params can be passed as desc argument, you can override any parameter except isIntersected

.leaveNode(node, desc)

Triggers all IntersectionObservers observing the node, with isIntersected set to false and intersectionRatio set to 0. Other IntersectionObserverEntry params can be passed as desc argument, you can override any parameter except isIntersected

.enterNodes(nodeDescriptions)

Triggers all IntersectionObservers observing the nodes in nodeDescriptions with multiple nodes entering at once. Each IntersectionObserver callback will receive only the nodes it's observing:

io.enterNodes([
  // you can pass multiple nodes each with its own state
  { node: screen.getByText('First Node'), desc: { intersectionRatio: 0.5 } },
  // description is optional:
  { node: screen.getByText('Second Node') },
  // or you can use a shorthand:
  screen.getByText('Third Node'),
]);

.leaveNodes(nodeDescriptions)

Triggers all IntersectionObservers observing the nodes in nodeDescriptions with multiple nodes leaving at once. Each IntersectionObserver callback will receive only the nodes it's observing.

.triggerNodes(nodeDescriptions)

Triggers all IntersectionObservers observing the nodes in nodeDescriptions with multiple nodes at once with custom descriptions (isIntersected is not enforced). Each IntersectionObserver callback will receive only the nodes it's observing

.enterAll(desc) and .leaveAll(desc)

Triggers all IntersectionObservers for each of the observed nodes

Mock ResizeObserver

Provides a way of triggering resize observer events. It's up to you to mock elements' sizes. If your component uses contentRect provided by the callback, you must mock element's getBoundingClientRect (for exemple using a helper function mockElementBoundingClientRect provided by the lib)

Currently the mock doesn't take into account multi-column layouts, so borderBoxSize and contentBoxSize will contain only one full-sized item

Example, using React Testing Library:

import {
  mockResizeObserver,
  mockElementBoundingClientRect,
} from 'jsdom-testing-mocks';

const DivWithSize = () => {
  const [size, setSize] = useState({ width: 0, height: 0 });
  const ref = useRef(null);

  useEffect(() => {
    const observer = new ResizeObserver(entries => {
      setSize({
        width: entries[0].contentRect.width,
        height: entries[0].contentRect.height,
      });
    });

    observer.observe(ref.current);

    return () => {
      observer.disconnect();
    };
  }, []);

  return (
    <div data-testid="theDiv" ref={ref}>
      {size.width} x {size.height}
    </div>
  );
};

const resizeObserver = mockResizeObserver();

it('prints the size of the div', () => {
  render(<DivWithSize />);

  const theDiv = screen.getByTestId('theDiv');

  expect(screen.getByText('0 x 0')).toBeInTheDocument();

  mockElementBoundingClientRect(theDiv, { width: 300, height: 200 });

  act(() => {
    resizeObserver.resize(theDiv);
  });

  expect(screen.getByText('300 x 200')).toBeInTheDocument();

  mockElementBoundingClientRect(theDiv, { width: 200, height: 500 });

  act(() => {
    resizeObserver.resize(theDiv);
  });

  expect(screen.getByText('200 x 500')).toBeInTheDocument();
});

API

mockResizeObserver returns an object, that has one method:

.resize(elements: HTMLElement | HTMLElement[])

Triggers all resize observer callbacks for all observers that observe the passed elements

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].