Giter VIP home page Giter VIP logo

jest-matcher-vue-test-utils's Introduction

jest-matcher-vue-test-utils

npm GitHub Workflow Status

Cute matchers for Jest to test Vue components with Vue Test Utils.

You can write tests for Vue component/store intuitively ⚡️

it("Emits 'select' event by clicking PrimaryButton", () => {
  const wrapper = shallowMount(Component);
  
  expect(wrapper.emitted().select).toBeUndefined();
  wrapper.find(PrimaryButton).vm.$emit("click");
  expect(wrapper.emitted().select[0]).toBeTruthy();
});

becomes

it("Emits 'select' event by clicking PrimaryButton", () => {
  const wrapper = shallowMount(Component);
  
  expect(() => {
    wrapper.find(PrimaryButton).vm.$emit("click");
  }).toEmit(wrapper, "select");
});

And all matchers have type definition and doc 💇‍♂️

190607_jest_matcher_infer

Installation

Get from npm:

$ npm install -D jest-matcher-vue-test-utils

Then, register matchers on your jest process:

import vueTestUtilMatchers from "jest-matcher-vue-test-utils";
expect.extend({ ...vueTestUtilMatchers });

Provided Matchers

Existence on Wrapper

toShow

Assert the function shows a content on Wrapper of vue-test-utils
// error-message.vue
<template>
  <div>
    <p v-if="isError" class="error">message</p>
  </div>
</template>

...

data: function () {
  return {
    isError: false
  }
},
methods: {
  showError () {
    this.isError = true;
  }
}
import Component from "./error-message.vue";

it("show error by showError", async () => {
  return expect(async () => {
    wrapper.vm.showError();
    await wrapper.vm.$nextTick();
  }).toShow(wrapper, "p.error"); // Passes
});

toHide

Assert the function hides a content on Wrapper of vue-test-utils
// error-message.vue
<template>
  <div>
    <p v-if="isError" class="error">message</p>
  </div>
</template>

...

data: function () {
  return {
    isError: true
  }
},
methods: {
  hideError () {
    this.isError = false;
  }
}
import Component from "./error-message.vue";

it("show error by showError", async () => {
  return expect(async () => {
    wrapper.vm.hideError();
    await wrapper.vm.$nextTick();
  }).toHide(wrapper, "p.error"); // Passes
});

Events on Wrapper

toEmit / toEmitOnRoot

Assert the action emits the event (with the payload optionally) on Wrapper of vue-test-utils
// event.vue
<template>
  <div @click="emitEvent('clicked')">
    Click Me
  </div>
</template>

<script>
module.exports = {
  methods: {
    emitEvent (e) {
      this.$emit("special", e);
    }
  }
}
</script>
import Component from "./event.vue";

it("emits special event by click", () => {
  const wrapper = shallowMount(Component);
  expect(() => wrapper.trigger("click")).toEmit(wrapper, "special"); // Passes
  expect(() => wrapper.trigger("click")).toEmit(wrapper, "special", "clicked"); // Passes
});

Async function is supported as well.

it("emits special event by click", async () => {
  const wrapper = shallowMount(Component);
  return expect(async () => triggersEventAsynchronously()).toEmit(wrapper, "special", "clicked"); // Passes
});

toEmitOnRoot inspects whether the event is emitted on $root of Vue instance.

toHaveEmitted / toHaveEmittedOnRoot

Assert the event is emitted (with the payload optionally) on Wrapper of vue-test-utils
// event.vue
<template>
  <div @click="emitEvent('clicked')">
    Click Me
  </div>
</template>

<script>
module.exports = {
  methods: {
    emitEvent (e) {
      this.$emit("special", e);
    }
  }
}
</script>
import Component from "./event.vue";

it("emits special event by click", () => {
  const wrapper = shallowMount(Component);
  wrapper.trigger("click");
  expect(wrapper).toHaveEmitted("special"); // Passes
  expect(wrapper).toHaveEmitted("special", "clicked"); // Passes
});

toHaveEmittedOnRoot inspects whether the event is emitted on $root of Vue instance.

Vuex actions/mutations

toDispatch

Assert the function dispatches Vuex action on the component
// click-store.vue
<template>
  <div @click="dispatchStore('click')">
    Click Me
  </div>
</template>

<script>
module.exports = {
  methods: {
    dispatchStore (e) {
      this.$store.dispatch('awesomeAction', e);
    }
  }
}
</script>
import Component from "./click-store.vue";

it("Dispatches the action on store by click", () => {
  const wrapper = shallowMount(Component);
  expect(() => {
    wrapper.trigger("click");
  }).toDispatch(wrapper, "awesomeAction"); // Passes

  expect(() => {
    wrapper.trigger("click");
  }).toDispatch(wrapper, "awesomeAction", 'click'); // Passes
});

Async function is supported as well.

it("dispatches the action on store by click", async () => {
  return expect(async () => {
    dispatchEventAsynchronosly();
  }).toDispatch(wrapper, "awesomeAction", 'click'); // Passes
});

toCommit (TBD)

Assert the store mutation is committed
// click-store.vue
<template>
  <div @click="commitStore('click')">
    Click Me
  </div>
</template>

<script>
module.exports = {
  methods: {
    commitStore (e) {
      this.$store.commit('importantMutation', e);
    }
  }
}
</script>
import Component from "./click-store.vue";

it("Commits the mutation on store by click", () => {
  const wrapper = shallowMount(Component);
  expect(() => {
    wrapper.trigger("click");
  }).toCommit(wrapper, "importantMutation"); // Passes

  expect(() => {
    wrapper.trigger("click");
  }).toCommit(wrapper, "importantMutation", 'click'); // Passes
});

toHaveDispatched

Assert a component has dispatched Vuex action
// click-store.vue
<template>
  <div @click="dispatchStore('click')">
    Click Me
  </div>
</template>

<script>
module.exports = {
  methods: {
    dispatchStore (e) {
      this.$store.dispatch('awesomeAction', e);
    }
  }
}
</script>
import Component from "./click-store.vue";
import { vuexPlugin } from "jest-matcher-vue-test-utils";

it("Dispatches the action on store by click", () => {
  const store = new Vuex.Store({
    actions: dispatchStore() {},
    plugins: [vuexPlugin()] // Requires adding plugin to use `toHaveDispatched` matcher
  });

  const wrapper = shallowMount(Component, { store })
  wrapper.trigger("click");
  expect(wrapper).toHaveDispatched("awesomeAction"); // Passes
  expect(wrapper).toHaveDispatched("awesomeAction", "click"); // Passes
});

Prop Validations

toBeValidProps

Assert that a prop set is valid for a component
// name-require-and-fullname-is-validated-component.vue
props: {
  name: {
    type: String,
    required: true
  }
  fullname: {
    validator: function (val) {
      return !!val && val.match(/.+\s.+/);
    }
  }
}
import Component from "./name-require-and-fullname-is-validated-component.vue";

it("component validates props", () => {
  expect(Component).toBeValidProps({ name: "required name", fullName: "Kengo Hamasaki" }); // Passes
  expect(Component).toBeValidProps({ fullName: "Kengo Hamasaki" }); // Fails
  expect(Component).toBeValidProps({ name: "required name", fullName: "Kengo" }); // Fails
});

toBeValidProp

Assert that a single prop is valid for a component
// name-require-component.vue
props: {
  name: {
    type: String,
    required: true
  }
}
import Component from "./name-require-component.vue";

it("component validates props", () => {
  expect(Component).toBeValidProp("name", "Required Name"); // Passes
  expect(Component).toBeValidProp("name", null); // Fails as required
  expect(Component).toBeValidProp("name", 123}); // Fails as typecheck
});

toRequireProp

Assert that a component requires a prop
// name-require-component.vue
props: {
  name: {
    type: String,
    required: true
  }
}
import Component from "./name-require-component.vue";

it("component requires name prop", () => {
  expect(Component).toRequireProp("name"); // Passes
  expect(Component).toRequireProp("birthday"); // Fails
});

toHaveDefaultProp

Assert that a component gives default to a prop
// default-address-component.vue
props: {
  address: {
    type: String,
    default: "Kitakyushu, Japan"
  }
}
import Component from "./default-address-component.vue";

it("component gives default value for address prop", () => {
  expect(Component).toHaveDefaultProp("address", "Kitakyushu, Japan"); // Passes
  expect(Component).toHaveDefaultProp("address", "San Francisco, US"); // Fails
});

toBeValidPropWithTypeCheck

Assert that a component validates a prop with type
// takes-zipcode-component.vue
props: {
  zipcode: {
    type: String
  }
}
import Component from "./takes-zipcode-component.vue";

it("component validates zipcode prop", () => {
  expect(Component).toBeValidPropWithTypeCheck("zipcode", "94103"); // Passes
  expect(Component).toBeValidPropWithTypeCheck("zipcode", 94103); // Fails
});

toBeValidPropWithCustomValidator

Assert that a component validates a prop with custom validator
// fullname-is-validated-component.vue
props: {
  fullname: {
    validator: function (val) {
      return !!val && val.match(/.+\s.+/);
    }
  }
}
import Component from "./fullname-is-validated-component.vue";

it("component validates fullname prop", () => {
  expect(Component).toBeValidPropWithCustomValidator("fullname", "Kengo Hamasaki"); // Passes
  expect(Component).toBeValidPropWithCustomValidator("fullname", "Kengo"); // Fails
});

Config

We can configure the matchers. Currently accepting mountOptions property to give options for shallowMount which is running in inside of matchers.

import vueTestUtilMatchers, { config } from "jest-matcher-vue-test-utils";
import { createLocalVue } from "@vue/test-utils";

config({
  mountOptions: { localVue: createLocalVue() }
});

License

MIT, Copyright (c) 2018- Kengo Hamasaki

jest-matcher-vue-test-utils's People

Contributors

dependabot[bot] avatar hmsk avatar renovate-bot avatar sobolevn 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  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

jest-matcher-vue-test-utils's Issues

Typescript error

Code:

import axios from 'axios'
import { NuxtAxiosInstance } from '@nuxtjs/axios'
import Vuex, { Store, ModuleTree } from 'vuex'
import { vuexPlugin } from 'jest-matcher-vue-test-utils'

import * as locations from '~/store/locations'
import { LocationsStateType } from '~/logic/locations/types'

export function locationsModule (): ModuleTree<LocationsStateType> {
  return {
    'locations': {
      'namespaced': true,
      ...locations,
    },
  }
}

/**
 * Custom Vuex Store creation optimized for tests.
 *
 * @param module - Vuex Module to be injected.
 */
export default function createStore <T> (module: ModuleTree<T>): Store<T> {
  // TODO: allow multiple modules at the same time
  const store = new Vuex.Store<T>({
    'modules': { ...module },
    'plugins': [vuexPlugin()],
  })
  store.$axios = axios as unknown as NuxtAxiosInstance

  return store
}

Output:

TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    tests/fixtures/vuex.ts:27:5 - error TS2322: Type '((store: Store<{}>) => void)[]' is not assignable to type 'Plugin<T>[]'.
      Type '(store: Store<{}>) => void' is not assignable to type 'Plugin<T>'.
        Types of parameters 'store' and 'store' are incompatible.
          Type 'Store<T>' is not assignable to type 'Store<{}>'.
            Types of property 'registerModule' are incompatible.
              Type '{ <T>(path: string, module: Module<T, T>, options?: ModuleOptions | undefined): void; <T>(path: string[], module: Module<T, T>, options?: ModuleOptions | undefined): void; }' is not assignable to type '{ <T>(path: string, module: Module<T, {}>, options?: ModuleOptions | undefined): void; <T>(path: string[], module: Module<T, {}>, options?: ModuleOptions | undefined): void; }'.
                Types of parameters 'module' and 'module' are incompatible.
                  Type 'Module<any, {}>' is not assignable to type 'Module<any, T>'.
                    Types of property 'actions' are incompatible.
                      Type 'ActionTree<any, {}> | undefined' is not assignable to type 'ActionTree<any, T> | undefined'.
                        Type 'ActionTree<any, {}>' is not assignable to type 'ActionTree<any, T>'.
                          Index signatures are incompatible.
                            Type 'Action<any, {}>' is not assignable to type 'Action<any, T>'.
                              Type 'ActionHandler<any, {}>' is not assignable to type 'Action<any, T>'.
                                Type 'ActionHandler<any, {}>' is not assignable to type 'ActionHandler<any, T>'.
                                  Type '{}' is not assignable to type 'T'.
                                    '{}' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.

    27     'plugins': [vuexPlugin()],
           ~~~~~~~~~

      node_modules/vuex/types/index.d.ts:96:3
        96   plugins?: Plugin<S>[];
             ~~~~~~~
        The expected type comes from property 'plugins' which is declared here on type 'StoreOptions<T>'

Solution: generate_plugin() should be generic.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • Replace dependency rollup-plugin-json with @rollup/plugin-json 4.0.0
  • Update actions/checkout action to v4
  • Update actions/setup-node action to v4
  • Update dependency rollup to v4
  • Update dependency typescript to v5
  • Update dependency vuex to v4
  • 🔐 Create all rate-limited PRs at once 🔐

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/nodejs.yml
  • actions/checkout v2
  • actions/setup-node v2
npm
package.json
  • expect >=23.0
  • jest-diff >=23.0
  • @types/jest 26.0.23
  • @vue/test-utils 1.2.0
  • babel-core 7.0.0-bridge.0
  • jest 26.6.3
  • jest-util 26.6.2
  • rollup 2.51.1
  • rollup-plugin-cleanup 3.2.1
  • rollup-plugin-commonjs 10.1.0
  • rollup-plugin-json 4.0.0
  • rollup-plugin-node-resolve 5.2.0
  • rollup-plugin-typescript2 0.30.0
  • ts-jest 26.5.6
  • typescript 4.3.2
  • vue 2.6.14
  • vue-jest 3.0.7
  • vue-template-compiler 2.6.14
  • vuex 3.6.2
  • @vue/test-utils ^1.0.0
  • jest >=23.0

  • Check this box to trigger a request for Renovate to run again on this repository

Claim target is not expected

  • wrapper on all matchers should be a wrapper by vue-test-utils
  • function for toEmit, toShow, toHide, toDispatch, toCommit should be a function

jest^24 support

Hi, the latest version of jest (^24.8.0) raises a warning when used with your plugin:

npm WARN [email protected] requires a peer of jest@^22.0.0 || ^23.0.0 but none is installed. You must install peer dependencies yourself.

Can we update jest version to the latest one?

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.