Git Product home page Git Product logo

cap-plugin-mock-jest's Introduction

Capacitor Plugin Mocks with Jest

Mocking a plugin in a unit test can be a challenge. Most mocking libraries mock an object by wrapping a JavaScript proxy around the object. Capacitor plugins, however, are already set up as JavaScript proxies, and you cannot create a proxy of a proxy. To get around this when using Jest as your testing framework, manual mocks is typically used.

The Manual Mocks

For this project, I am using two Capacitor plugins: @capacitor/storage and @capacitor/toast. To create manual mocks for these plugins, I create the following file structure at the root of the project:

.
|
+- __mocks__
| |
| +- @capacitor
|   |
|   +- storeage.ts
|   +- toast.ts
...
+- src

The code in these files create some simple stubs that I use within the tests. For example:

storeage.ts

export const Storage = {
  async get(data: { key: string }): Promise<{ value: string | undefined }> {
    return { value: undefined };
  },

  async set(data: { key: string; value: string }): Promise<void> {},
  async clear(): Promise<void> {},
};

toast.ts

export const Toast = {
  async show(data: {
    text: string;
    duration?: 'short' | 'long';
    position?: 'bottom' | 'center' | 'top';
  }): Promise<void> {},
};

As you can see, they do almost nothing, which is exactly what you want stubs to do.

When I want to have fine-grained control in my tests, I can create mocks on the stubs and have complete control over my tests. For example, here is a test for an @ionic/vue application that controls the return value for Storage.get():

  it("gets the first and last name", async () => {
    Storage.get = jest.fn().mockImplementation(
      async (data: { key: string }): Promise<{ value: string }> => {
        return data.key === "firstName"
          ? { value: "Jimmy" }
          : data.key === "lastName"
          ? { value: "Simms" }
          : { value: "unknown" };
      }
    );
    const w = mount(Home);
    await flushPromises();
    expect(w.vm.firstName).toEqual("Jimmy");
    expect(w.vm.lastName).toEqual("Simms");
  });

The combination of the Jest manual mocks and the standard Jest mocks provides this level of control.

Conclusion

Adding manual mocks to provide stubs for the Capacitor plugins we are using helps to make our unit tests clean and maintainable.

Happy Testing, Everybody!! ๐Ÿค“

cap-plugin-mock-jest's People

Contributors

kensodemann avatar mlynch avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cap-plugin-mock-jest's Issues

Issues mocking `CapacitorHttp` in jest

Dear Ionic Team, could you please make an example mocking plugins (or parts of the module) from @capacitor/core

After several hours of trying, I wasn't able to mock this plugin, mostly running into ReferenceError: fetch is not defined which I believe suggests that CapacitorHttp.get() or CapacitorHttp.reuqest() calls were NOT mocked.

Using @capacitor/core": "^4.6.1", @angular/core": "14.2.2", "@ionic/angular": "^6.0.1", "jest": "28.1.1",

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.