微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vue3 测试库 - 如何在测试中使用 globalProperties

如何解决vue3 测试库 - 如何在测试中使用 globalProperties

我是 Vue 的新手,并遵循了使用 vue 测试库的建议。唯一的问题是我似乎找不到将代码注入到渲染函数中的 globalProperties 的方法

有人知道我可以注入或模拟它的示例吗?

ma​​in.js

app.config.globalProperties.$globals = globalMethods

...
const app = createApp(App)
app.config.globalProperties.$globals = globalMethods
app.config.globalProperties.$globalVars = globalVars

app.component("font-awesome-icon",fontawesome)

app.use(applicationStore);
app.use (Hotjar,hotjarConfig)
app.use(i18n)
app.use(router)

app.mount('#app')

从我创建的 vue 组件中,我可以调用

Component.vue

let formatedobj = this.$globals.maskValues(this.inputValue,this.inputType,this);

...,created() {
    let formatedobj = this.$globals.maskValues(this.inputValue,this);
    this.myInputValue = formatedobj.formatedString;
    this.formatedCharacterCount = formatedobj.formatedCharacterCount;
    this.prevValue = this.myInputValue;
  },...

test.spec.js

import { render } from '@testing-library/vue'
import FormatednumericInput from '@/components/Component.vue'
import {globalMethods} from'@/config/global-methods'


const label = 'Price'
const initSettings = {
  props: {
    inputId: 'testInputId1',labelTxt: label
  }
};

beforeEach(() => {
});

test('a simple string that defines your test',() => {

  const { getByLabelText } = render(FormatednumericInput,initSettings)
  const input = getByLabelText(label)
  
  // testing logic
  expect(input != null).toBe(true)
  expect(FormatednumericInput != null).toBe(true)

})

** 错误 **

TypeError: Cannot read property 'maskValues' of undefined

      85 |   },86 |   created() {
    > 87 |     let formatedobj = this.$globals.maskValues(this.inputValue,this);
         |                                     ^
      88 |     this.myInputValue = formatedobj.formatedString;
      89 |     this.formatedCharacterCount = formatedobj.formatedCharacterCount;
      90 |     this.prevValue = this.myInputValue;

      at Proxy.created (src/components/FormatednumericInput.vue:87:37)

解决方法

second argument of render() 被传递给 @vue/test-utils mount(),因此您可以包含 global.mocks mounting option 来模拟 $globals.maskValues

const { getByLabelText } = render(FormatedNumericInput,{
  ...initSettings,global: {
    mocks: {
      $globals: {
        maskValues: (inputValue,inputType) => {
          const formatedString = globalFormatValue(inputValue) // declared elsewhere
          return {
            formatedString,formatedCharacterCount: formatedString.length,}
        }
      }
    }
  }
})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。