GithubHelp home page GithubHelp logo

joshuakgoldberg / mock-react-redux Goto Github PK

View Code? Open in Web Editor NEW
20.0 10.0 5.0 529 KB

Mocks out Redux actions and selectors for clean React Jest tests. 🎭

License: MIT License

TypeScript 96.48% JavaScript 3.52%
react react-redux redux testing unit-tests usedispatch useselector hacktoberfest

mock-react-redux's Introduction

🎭 mock-react-redux

Code Style: Prettier TypeScript: Strict NPM version

Mocks out Redux actions and selectors for clean React Jest tests.

Tired of setting up, updating, and debugging through complex Redux states in your React tests? Use this package if you'd like your React component tests to not take dependencies on your full Redux store.

See FAQs for more backing information. 📚

Usage

import { mockReactRedux } from "mock-react-redux";

mock-react-redux stubs out connect and the two common Redux hooks used with React components. Call mockReactRedux() before your render/mount logic in each test.

Mocking State

mockReactRedux().state({
  title: "Hooray!",
});

Sets a root state to be passed to your component's selectors.

it("displays the title when there is a title", () => {
  mockReactRedux().state({
    title: "Hooray!",
  });

  // state => state.title
  const view = render(<RendersTitle />);

  view.getByText("Hooray!");
});

See Selectors for more documentation or Heading for a code example.

Mocking Selectors

mockReactRedux()
  .give(valueSelector, "Hooray!")
  .giveMock(fancySelector, jest.fn().mockReturnValueOnce("Just the once."));

Provide results to the useSelector function for individual selectors passed to it. These work similarly to Jest mocks: .give takes in the return value that will always be passed to the selector.

it("displays the title when there is a title", () => {
  mockReactRedux().give(selectTitle, "Hooray!");

  // state => state.title
  const view = render(<RendersTitle />);

  view.getByText("Hooray!");
});

If you'd like more control over the return values, you can use .giveMock to provide a Jest mock.

See Selectors for more documentation or Heading for a code example.

Dispatch Spies

const { dispatch } = mockReactRedux();

The dispatch function returned by useDispatch will be replaced by a jest.fn() spy. You can then assert against it as with any Jest mock in your tests:

it("dispatches the pageLoaded action when rendered", () => {
  const { dispatch } = mockReactRedux();

  // dispatch(pageLoaded())
  render(<DispatchesPageLoaded />);

  expect(dispatch).toHaveBeenCalledWith(pageLoaded());
});

See Dispatches for more documentation or Clicker for a code example.

Gotchas

  • The first mock-react-redux import must come before the first react-redux import in your test files.
  • .give and .giveMock will only apply when selectors are passed directly to useSelector (e.g. useSelector(selectValue)).
    • See FAQs for more tips and tricks.
  • Thunks often create new functions per dispatch that make toBeCalledWith-style checks difficult. See the Thunks docs for details.

Hybrid Usage

You don't have to use mock-react-redux in every test file in your repository. Only the test files that import mock-react-redux will have react-redux stubbed out.

TypeScript Usage

mock-react-redux is written in TypeScript and generally type safe.

  • mockReactRedux() has an optional <State> type which sets the type of the root state passed to .state.
  • .give return values must match the return types of their selectors.
  • .giveMock mocks must match the return types of their selectors.

Heck yes. 🤘

Development

Requires:

After forking the repo from GitHub:

git clone https://github.com/<your-name-here>/mock-react-redux
cd mock-react-redux
yarn

Contribution Guidelines

We'd love to have you contribute! Check the issue tracker for issues labeled accepting prs to find bug fixes and feature requests the community can work on. If this is your first time working with this code, the good first issue label indicates good introductory issues.

Please note that this project is released with a Contributor Covenant. By participating in this project you agree to abide by its terms. See CODE_OF_CONDUCT.md.

mock-react-redux's People

Contributors

dependabot[bot] avatar gitter-badger avatar jakemhiller avatar jenesh avatar joshuakgoldberg avatar renovate[bot] avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mock-react-redux's Issues

Add support for Vitest

#62 necessitates either:

  • Using Jest instead of Vitest in the new tempalting
  • Adding support for Vitest (#61)

I think adding support for Vitest is the better path forward. Marking #58 and #62 as blocked on this.

Throw errors on other unsupported APIs provided by react-redux

connectAdvanced is cool and we may want to support it in mock-redux. Until then, there should be an explicit error thrown when attempting to use it. Otherwise it'll be confusing for consumers to see error messages like 'connectAdvanced' is not a function (which happens now, because mock-redux completely mocks the react-redux module).

See "API Reference" in https://react-redux.js.org/api for the full list of APIs that should have errors thrown. See how mockReactRedux.ts handles Provider for reference on what this issue is asking for.

Example AsyncThunks

Hi first of all thanks for the library! It make it easy the mock of redux!

I'm looking for examples to implement an async actions but without success.

It's posible with the current implementation, make tests for async thunk actions?

I've tryed with the Examples but without success.

I'm trying with the current code (importing original async action)

test("Should dispatch if all fields exists and were validated", async () => {
    const { dispatch } = mockReactRedux();

    const mockedSubmit = jest.fn().mockImplementation(() => {
      dispatch(newContact(values));
    });

    render(<ContactForm onSubmit={mockedSubmit} />);

    userEvent.type(screen.getByPlaceholderText("Nombre"), "John");
    userEvent.type(screen.getByPlaceholderText("Email"), "[email protected]");
    userEvent.type(screen.getByPlaceholderText("Teléfono"), "23456789");
    userEvent.type(screen.getByPlaceholderText("Escribe tu mensaje"), "Lorem ipsum dolor sit");

    userEvent.click(screen.getByTestId("contactButton"));

    await waitFor(() => {
      expect(dispatch).toHaveBeenCalled();
      expect(dispatch).toHaveBeenCalledWith(newContact(values));
    });
  });

But the result is:
image

I think maybe is for the thunk middleware.

PD: Sorry if my english is not good, I'm still learning!

Best Regards!

Support default imports

Here's how you import mockRedux right now:

import { mockRedux } from "mock-redux";

There's no real reason why we wouldn't be able to support this:

import mockRedux from "mock-redux";

If you'd like this to be doable, feel free to send a pull request adding it in!

Allow inline selectors

As of right now, anonymous or otherwise un-exported functions passed to useSelector will cause mockRedux to intentionally throw a "no mock defined" error:

useSelector(state => state.value);
useSelector(state => selectValue(state, someArgument));

const declaredInComponent = state => state.value;
useSelector(declaredInComponent);

Not good. Inline lambdas are a common recommended way to work with Redux.

Personally, the use cases I'm most excited about mock-redux for are the ones where a single named function that's mocked out is passed to useSelector, so there's no reliance on the Redux state in React view tests... but that's opinion not going to hold up for most applications - including the one(s) at Codecademy we've been discussing using this for.

In theory the mockRedux function could take in an optional state:

mockRedux({
  value: 'hi',
});

// 'hi'
useSelector(state => state.value);

In this world, the mocked useSelector would then only throw the "no mock defined" error for unknown selector functions if no state is defined.

I'm a little wary of dedicating the first argument to be exclusively used for this one use case, so perhaps mockRedux should instead take in an optional options object with an optional state member:

mockRedux({
  state: {
    value: 'hi',
  },
});

Edit: Ooh, actually I really like the sound of adding another fluent function:

mockRedux()
  .state({
    value: 'hi',
  });

...and maybe mockRedux should be typed in TypeScript land as mockRedux<State = any>? TypeScript-happy consumers could then re-export a version of the function with their application's state as the type.

Open to and hoping for a discussion here. Is this the right approach? If so, is this the right API?

Errors in older node environments for export * syntax

I've spotted this error in CircleCI:

/root/project/node_modules/mock-redux/src/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from "./mockRedux";
                                                                                         ^^^^^^
SyntaxError: Unexpected token 'export'

The culprit was changing tsconfig.json to output ES module syntax instead of CommonJS. I did that because Jest will complain about using module members in mocked modules if the module name doesn't begin with "mock" (even if the member name does):

import { mockFoo } from 'somewhere';

// Not allowed
jest.mock('other', () => () => mockFoo);

This can always be worked around with something like:

import * as somewhere from 'somewhere';

const { mockFoo } = somewhere;

Investigate Provider support

Following #8: can the standard Provider component be supported? Should it? 🤷

If you have opinions, please do post them on this issue (or contact me directly if you're shy!). It'd be great to have an understanding of whether mocking Provider is something this library will reasonably need to do.

Consider allowing usage outside describe()s to set up base state

If you want the same state to be set in all unit tests in a file, this is how you do it now:

describe('...', () => {
  beforeEach(() => {
    mockReactRedux().state({ value: true });
  });

  it('...', () => {/* ... */});
});

What if mockReactRedux() could be called in all its normal ways outside a test to apply some defaults?

mockReactRedux().state({ value: true });

describe('...', () => {
  it('...', () => {/* ... */});
});

Create some kind of "docs/Philosophy.md" page

There are going to be a lot of opinions thrown around about how to test connected React components.

  • Is this a good way to isolate from Redux?
  • Is isolating from Redux in the first place the right approach?
  • What are the pros and cons of this and other approaches?

These and other questions would do well in a docs page, linked in the README.md, that itself links to other good resources (e.g. https://react-redux.js.org/api/hooks#additional-considerations-when-using-hooks).

Support connect() usage

Had a good brief chat about downsides with @ian-craig, who brought up the good point that only targeted hook usage leaves out all applications that use connect().

In theory it should be possible to support connect(). Let's do it!

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.