简体   繁体   English

VueJS 和 Jest。 使用本地导入的 mixin 测试组件

[英]VueJS and Jest. Testing component with local imported mixin

I am learning VueJS by recreating MineOS interface.我正在通过重新创建 MineOS 界面来学习 VueJS。 I have replicated a bunch of functionality without actually calling the backend.我在没有实际调用后端的情况下复制了一堆功能。 I've run into an issue with unit testing.我遇到了单元测试的问题。 It looks like I've done everything I can but I think that my mixin method isn't being called.看起来我已经做了我能做的一切,但我认为我的 mixin 方法没有被调用。 I think what I am doing is:我认为我正在做的是:

  1. mocking the store/state with my test (which I have done in my login spec).用我的测试模拟商店/状态(我在我的登录规范中做过)。
  2. mocking the action that the mixin uses and assigning to the store, which should be mapped in the mixin.模拟 mixin 使用并分配给 store 的操作,这应该映射到 mixin 中。
  3. populating the java_xmx input with 235 and then triggering the input event.用 235 填充 java_xmx 输入,然后触发输入事件。
  4. trigger next tick触发下一个滴答
  5. interrogate the action to see if it's been called.询问操作以查看它是否被调用。

Is the only way to test with mixins to import globally and mock?使用mixin进行测试以全局导入和模拟的唯一方法是什么?

javaoptions.vue javaoptions.vue

<template>
  <div class="tile is-vertical">
    <div class="tile is-child has-text-left">
      <b-dropdown
        aria-role="list"
        @change="updateConfig('java', 'jarfile', $event)"
      >
        <template #trigger="{ active }">
          <b-button
            label="Change runnable JAR to:"
            :icon-right="active ? 'menu-up' : 'menu-down'"
          />
        </template>
        <b-dropdown-item aria-role="listitem" value="minecraft_server_17.1.jar"
          >minecraft_server_17.1.jar</b-dropdown-item
        >
      </b-dropdown>
    </div>
    <div class="tile is-child has-text-left">
      <div class="tile">
        <b-field label="Memory Allocation (Heapsize)">
          <div class="tile is-vertical">
            <div class="tile is-child">
              <b-field class="has-addons">
                <p class="control">
                  <b-button class="button is-static">-Xmx</b-button>
                </p>
                <b-input
                  id="java_xmx"
                  :lazy="true"
                  type="number"
                  @input="updateConfig('java', 'java_xmx', $event)"
                ></b-input>
                <p class="control">
                  <b-button class="button is-static">MB</b-button>
                </p>
              </b-field>
            </div>
            <div class="tile is-child">
              <b-field class="has-addons">
                <p class="control">
                  <b-button class="button is-static">-Xms</b-button>
                </p>
                <b-input
                  id="java_xms"
                  type="number"
                  :lazy="true"
                  @input="updateConfig('java', 'java_xms', $event)"
                ></b-input>
                <p class="control">
                  <b-button class="button is-static">MB</b-button>
                </p>
              </b-field>
            </div>
            <div class="tile is-child">
              <b-field label="Additional Java arguments:">
                <b-input
                  id="java_tweaks"
                  placeholder="-XX:+DisableExplicitGC"
                  :lazy="true"
                  @input="updateConfig('java', 'java_tweaks', $event)"
                />
              </b-field>
            </div>
            <div class="tile is-child">
              <b-field label="Additional Jar arguments:">
                <b-input
                  id="jar_args"
                  placeholder="nogui"
                  :lazy="true"
                  @input="updateConfig('java', 'jar_args', $event)"
                />
              </b-field>
            </div>
          </div>
        </b-field>
      </div>
    </div>
  </div>
</template>

<script>
import updateConfigMixin from '@/mixins/updateconfig-mixin.js';

export default {
  name: 'JavaOptions',
  mixins: [updateConfigMixin],
  computed: {},
  methods: {},
};
</script>

<style lang="scss" scoped></style>

JavaSettings.spec.js JavaSettings.spec.js

import { mount, createLocalVue } from '@vue/test-utils';
import JavaOptions from '@/components/partials/java_settings/javaoptions.vue';
import Buefy from 'buefy';
import Vuex from 'vuex';

const localVue = createLocalVue();

localVue.use(Vuex);
localVue.use(Buefy);

describe('JavaOptions.vue', () => {
  let actions;
  let store;

  beforeEach(() => {
    actions = {
      updateServerConfigAction: jest.fn(),
    };

    store = new Vuex.Store({
      actions,
      selected: { config: { java_xmx: '' } },
    });
  });

  it("expect 'updateServerConfigAction' to be called on setting change", async () => {
    const wrapper = mount(JavaOptions, {
      store,
      localVue,
      attachTo: document.body,
    });

    const java_xmx = wrapper.find('#java_xmx');
    java_xmx.element.value = 235;
    java_xmx.trigger('input');
    await wrapper.vm.$nextTick();
    expect(java_xmx.element.value).toBe('235');
    expect(wrapper.vm.updateServerConfigAction).toHaveBeenCalled();
  });
});

updateconfig-mixin.js updateconfig-mixin.js

import cloneDeep from 'clone-deep';
import { mapActions, mapState } from 'vuex';

export default {
  computed: {
    ...mapState({ config: state => state.selected.config }),
  },
  methods: {
    ...mapActions(['updateServerConfigAction']),
    updateConfig(section, propKey, newVal) {
      const config = cloneDeep(this.config);
      const selectedSection = config[section];
      selectedSection[propKey] = newVal;
      this.updateServerConfigAction(config);
    },
  },
};

TERMINAL OUTPUT端子输出

peter@peter-VirtualBox:/usr/development/mineos-vue$ npm run -s test:unit
 FAIL  tests/unit/JavaSettings.spec.js
  ● JavaOptions.vue › expect 'updateServerConfigAction' to be called on setting change

    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      36 |     await wrapper.vm.$nextTick();
      37 |     expect(java_xmx.element.value).toBe('235');
    > 38 |     expect(actions.updateServerConfigAction).toHaveBeenCalled();
         |                                              ^
      39 |   });
      40 | });
      41 |

      at Object.it (tests/unit/JavaSettings.spec.js:38:46)

 PASS  tests/unit/Login.spec.js
-----------------------------------|----------|----------|----------|----------|-------------------|
File                               |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------------------------------|----------|----------|----------|----------|-------------------|
All files                          |       50 |      100 |    33.33 |       50 |                   |
 components/partials               |      100 |      100 |      100 |      100 |                   |
  Login.vue                        |      100 |      100 |      100 |      100 |                   |
 components/partials/java_settings |      100 |      100 |      100 |      100 |                   |
  javaoptions.vue                  |      100 |      100 |      100 |      100 |                   |
 mixins                            |        0 |      100 |        0 |        0 |                   |
  updateconfig-mixin.js            |        0 |      100 |        0 |        0 |     6,11,12,13,14 |
-----------------------------------|----------|----------|----------|----------|-------------------|

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.063s
Ran all test suites.

Figured it out finally!终于想通了!

There were a couple of issues that required fixing for the entire test to pass.有几个问题需要修复才能通过整个测试。 The issue at hand was that the mixin didn't appear to be utilised in the test.手头的问题是 mixin 似乎没有在测试中使用。 I required to change @input="updateConfig('java', 'java_xmx', $event)" to @input.native="updateConfig('java', 'java_xmx', $event)" of course!我当然需要将@input="updateConfig('java', 'java_xmx', $event)"更改为@input.native="updateConfig('java', 'java_xmx', $event)" .native . .native .

I then discovered that I hadn't mocked my state and had to do that.然后我发现我没有嘲笑我的状态,并且必须这样做。

The final code for the test is测试的最终代码是

import { mount, createLocalVue } from '@vue/test-utils';
import JavaOptions from '@/components/partials/java_settings/javaoptions.vue';
import Buefy from 'buefy';
import Vuex from 'vuex';

const localVue = createLocalVue();

localVue.use(Vuex);
localVue.use(Buefy);

describe('JavaOptions.vue', () => {
  let actions;
  let store;

  beforeEach(() => {
    actions = {
      updateServerConfigAction: jest.fn(),
    };

    store = new Vuex.Store({
      actions,
      state: { selected: { config: { java: { java_xmx: '' } } } },
    });
  });

  it("expect 'updateServerConfigAction' to be called on setting change", async () => {
    const wrapper = mount(JavaOptions, {
      store,
      localVue,
      attachTo: document.body,
    });

    const java_xmx = wrapper.find('#java_xmx');
    await java_xmx.setValue(235);

    expect(java_xmx.element.value).toBe('235');
    expect(actions.updateServerConfigAction).toHaveBeenCalled();
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM