2

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

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

main.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 组件中,我可以调用

组件.vue

让 formatedObj = this.$globals.maskValues(this.inputValue, this.inputType, this);

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

测试规范.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.inputType, 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)
4

1 回答 1

0

第二个参数render()被传递给@vue/test-utils mount(),因此您可以在mock 中包含global.mocks安装选项$globals.maskValues

const { getByLabelText } = render(FormatedNumericInput, {
  ...initSettings,
  global: {
    mocks: {
      $globals: {
        maskValues: (inputValue, inputType) => {
          const formatedString = globalFormatValue(inputValue) // declared elsewhere
          return {
            formatedString,
            formatedCharacterCount: formatedString.length,
          }
        }
      }
    }
  }
})
于 2021-07-30T04:42:59.730 回答