标签: vue-test-utils

Vue3 的 Vue 测试实用程序:文档未定义

我尝试根据以下内容引导一个简单的应用程序Vue3,,ViteVitest

\n

我还安装了 vue 3 兼容版本的vue test utils来测试 vue 组件。

\n

我在尝试复制文档中的基本示例时遇到错误:

\n
import { mount } from "@vue/test-utils";\nimport { expect, test } from \'vitest\'\n\n\n// The component to test\nconst MessageComponent = {\n  template: "<p>{{ msg }}</p>",\n  props: ["msg"],\n};\n\ntest("displays message", () => {\n  const wrapper = mount(MessageComponent, {\n    props: {\n      msg: "Hello world",\n    },\n  });\n\n  // Assert the rendered text of the component\n  expect(wrapper.text()).toContain("Hello world");\n});\n\n
Run Code Online (Sandbox Code Playgroud)\n
 FAIL  src/tests/hello-world.test.ts > displays message\nReferenceError: document is not defined\n …
Run Code Online (Sandbox Code Playgroud)

vue.js vue-test-utils vite

20
推荐指数
3
解决办法
1万
查看次数

如何测试从VueX监视计算属性的Vue观察器?

假设我具有以下组件:

import { mapState } from 'vuex';
import externalDependency from '...';

export default {
  name: 'Foo',
  computed: {
    ...mapState(['bar'])
  },
  watch: {
    bar () {
     externalDependency.doThing(this.bar);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在测试时,我想确保使用externalDependency.doThing()调用bar(来自vuex状态),如下所示:

it('should call externalDependency.doThing with bar', () => {
  const wrapper = mount(Foo);
  const spy = jest.spyOn(externalDependency, 'doThing');

  wrapper.setComputed({bar: 'baz'});

  expect(spy).toHaveBeenCalledWith('baz');
});
Run Code Online (Sandbox Code Playgroud)

Vue的test-utils有一个setComputed方法,该方法可以让我目前对其进行测试,但是我不断收到警告,称setComputed将很快被删除,而且我不知道该如何进行测试:

https://github.com/vuejs/vue-test-utils/issues/331

javascript vue.js vuex vue-test-utils

15
推荐指数
2
解决办法
1710
查看次数

测试套件无法运行 import.meta.env.VITE_*

在我的代码中添加环境变量后import.meta.env.VITE_*,使用 vue-test-utils 的测试开始失败,并出现错误:

Jest suite failed to run
error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node12', or 'nodenext'.
Run Code Online (Sandbox Code Playgroud)

我已经搜索了一些可用的修复程序,但到目前为止没有一个有效。

编辑

jest.config.js 文件:

module.exports = {
  preset: "ts-jest",
  globals: {},
  testEnvironment: "jsdom",
  transform: {
    "^.+\\.vue$": "@vue/vue3-jest",
    "^.+\\js$": "babel-jest"
  },
  moduleFileExtensions: ["vue", "js", "json", "jsx", "ts", "tsx", "node"],
  moduleNameMapper: {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
      "<rootDir>/tests/unit/__mocks__/fileMock.js",
    "^@/(.*)$": "<rootDir>/src/$1"
  }
}
Run Code Online (Sandbox Code Playgroud)

tsconfig.json 文件:

{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": ["env.d.ts", "src/**/*", "src/**/*.vue", "tests"],
  "compilerOptions": {
    "module": "esnext", …
Run Code Online (Sandbox Code Playgroud)

vue.js jestjs vue-test-utils vite

15
推荐指数
2
解决办法
2万
查看次数

如何使用Jest对Vue.js组件中的方法进行单元测试

我正在尝试对组件方法进行单元测试。这里的问题并未提出如何从单元测试中访问组件方法。

具体来说,给定下面的Vue组件,如何doSomeWork()从单元测试中访问?

Vue组件:

<template>
    <div id="ThisStuff">
        <span>
            Some other stuff is going on here
        </span>
    </div>
</template>

<script>
    import foo from 'bar'

    export default {
        props: {
            ObjectWithStuffInIt: [
                {
                    id: 1
                    bar: false
                },
                {
                    id: 2
                    bar: false
                },
            ]
        },
        data: {
            foo: "foo"
        },
        methods: {
            doSomeWork: function() {
                for (var i = 0; i < ObjectWithStuffInIt.length; i++) { 
                    if (foo === "diddly") {
                        ObjectWithStuffInIt[i].bar = true;
                    }
                }
            }
        }
    } …
Run Code Online (Sandbox Code Playgroud)

unit-testing vue.js jestjs vuejs2 vue-test-utils

14
推荐指数
1
解决办法
9934
查看次数

如何使用Jest + Vuejs模拟window.location.href?

目前,我正在为我的项目实施单元测试,并且其中包含一个文件window.location.href

我想对此进行测试,这是我的示例代码:

it("method A should work correctly", () => {
      const url = "http://dummy.com";
      Object.defineProperty(window.location, "href", {
        value: url,
        writable: true
      });
      const data = {
        id: "123",
        name: null
      };
      window.location.href = url;
      wrapper.vm.methodA(data);
      expect(window.location.href).toEqual(url);
    });
Run Code Online (Sandbox Code Playgroud)

但是我得到这个错误:

TypeError: Cannot redefine property: href
        at Function.defineProperty (<anonymous>)
Run Code Online (Sandbox Code Playgroud)

我尝试了一些解决方案,但没有解决。我需要一些提示来帮助我摆脱困境。请帮助。

unit-testing jasmine vue.js vuejs2 vue-test-utils

14
推荐指数
8
解决办法
2万
查看次数

使用 Vue Test Utils,如何检查按钮是否被禁用?

我正在测试 Vue 组件,但在测试按钮的禁用状态时遇到问题。如何在测试中访问按钮的禁用状态?

我尝试过使用,.attributes()但在这种情况下,该方法仅返回未由v-bind. SubmitButton.attributes().disabled总是null

成分

<button
  id="edit-resource-modal-submit"
  class="btn btn-sm btn-primary modal-button"
  :disabled="loadingResource || !formValid"
  @click="submit"
>
  Save
</button>
Run Code Online (Sandbox Code Playgroud)

测试

describe('Disables buttons if', () => {
  beforeEach(async() => {
    await wrapper.setProps({ isModalOpen: true });
  });
  it('modal is loading', async() => {
    wrapper.vm.loadingResource = true;
    const SubmitButton = wrapper.find('#edit-resource-modal-submit');
    expect(SubmitButton.exists()).toBe(true);
    expect(SubmitButton.attributes().disabled).toBe('true');
  });
});

Run Code Online (Sandbox Code Playgroud)

.attributes() 仅返回

{
  id: 'edit-resource-modal-submit',
  class: 'btn btn-sm btn-primary modal-button'
}
Run Code Online (Sandbox Code Playgroud)

vue.js jestjs vue-test-utils vue-testing-library

12
推荐指数
2
解决办法
1万
查看次数

如何测试自定义输入Vue组件

在Vue.js文档中,有一个自定义输入组件的示例.我试图找出如何为这样的组件编写单元测试.组件的用法如下所示

<currency-input v-model="price"></currency-input>
Run Code Online (Sandbox Code Playgroud)

完整的实施可以在https://vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events找到

文件说

因此,对于要使用的组件v-model,它应该(这些可以在2.2.0+中配置):

  • 接受价值道具
  • 使用新值发出输入事件

我如何编写一个单元测试来确保我已经编写了这个组件以便它可以使用v-model?理想情况下,我不想专门测试这两个条件,我想测试一下行为,当组件内的值发生变化时,它也会在模型中发生变化.

vue.js vuejs2 vue-test-utils

11
推荐指数
1
解决办法
6596
查看次数

Vue-Test-Utils未知自定义元素:<router-link>

我正在使用Jest使用vue-test-utils库来运行我的测试.

即使我已经将VueRouter添加到localVue实例,它也说它实际上找不到路由器链接组件.如果代码看起来有点时髦,那是因为我使用TypeScript,但它应该非常接近ES6 ...主要的是@Prop()与传递道具相同:{..}

Vue组件:

<template>
  <div>
    <div class="temp">
      <div>
        <router-link :to="temp.url">{{temp.name}}</router-link>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import { Prop } from 'vue-property-decorator'
import { Temp } from './Temp'

@Component({
  name: 'temp'
})
export default class TempComponent extends Vue {
  @Prop() private temp: Temp
}
</script>

<style lang="scss" scoped>
.temp {
  padding-top: 10px;
}
</style>
Run Code Online (Sandbox Code Playgroud)

临时模型:

export class Temp {
  public static Default: Temp = new Temp(-1, '')

  public url: string

  constructor(public …
Run Code Online (Sandbox Code Playgroud)

jestjs vue-router vue-component vuejs2 vue-test-utils

11
推荐指数
2
解决办法
4724
查看次数

使用 `vue-test-utils` 和 `jest` 使用 `Created` 钩子进行测试

我有一个像这样的 Vue 页面:

<template>
</template>

<script>
created(){
    this.doSomething();
}

methods: {
    doSomething() {
        .....
    }
}

</script>
Run Code Online (Sandbox Code Playgroud)

现在,我们要测试这个创建的钩子并检查 doSomething() 方法是否被调用。

这样试过,jest也是在package.json中导入的

import {
  shallowMount,
  createLocalVue,
} from '@vue/test-utils';

const localVue = createLocalVue();

import Xyx from '/Xyx.vue';

const init = () => {
  wrapper = shallowMount(Xyx, { localVue });
  cmp = wrapper.vm;
};

describe('#created', () => {
  it('#doSomething', () => {
    init();
    wrapper.setMethods({
      doSomething: jest.fn(),
    })
    expect(cmp.doSomething).toHaveBeenCalled();
  });
});
Run Code Online (Sandbox Code Playgroud)

我可以做这个创建的钩子的单元测试用例吗?

vue.js jestjs vuex vue-test-utils

11
推荐指数
2
解决办法
8449
查看次数

Vue 3 + Vuetify 3 + vue/test-utils 的组合,导致“无法找到注入的 Vuetify 布局”错误

有谁知道如何@vue/test-utils v2在使用Vuetify 3 Beta版本时在库中进行组件测试?我也用它Vue3 composition API来定义我的组件。我在这里找到的文档https://vuetifyjs.com/en/getting-started/unit-testing/#spec-tests不起作用,因为它适用于Vuetify v2@vue/test-utils v1

这是我的plugins/vuetify.js

import '@mdi/font/css/materialdesignicons.css';
import 'vuetify/styles';
import { createVuetify } from 'vuetify';

export default createVuetify();
Run Code Online (Sandbox Code Playgroud)

这是我在 NavBar.spec.js 中的代码

import { mount } from '@vue/test-utils';
import NavBar from '../NavBar.vue';
import Vuetify from '../../plugins/vuetify';

describe('NavBar', () => {
    it('No properties [correct]', () => {
        mount(NavBar, {
            props: {},
            global: {
                plugins: [Vuetify]
            }
        });
        // check if navbar renders
        cy.get('.main')
            .first();

    });
});
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误: …

components vuetify.js vue-test-utils vuejs3

11
推荐指数
1
解决办法
8342
查看次数