安装方法给出错误消息 - Nuxt.js, Jest

mounted method giving error message - Nuxt.js, Jest

我是单元测试新手,对组件内部的挂载方法有疑问。

我正在测试按钮文本是否正确显示取决于其中一个数据值,并且它通过了。但是,我在组件内的 mounted() 中有一个方法并请求 API 从 nuxt 上下文调用的调用。

该方法失败并从 try 和 catch 中获取错误消息,因为看起来它无法在测试中找到 nuxt 上下文。这不影响我的测试,但我想知道它是否正常,或者我是否需要修复某些东西。

这是我的组件。

    <template>
        <button>
            {{variations.length > 0 ? 'Select options' : 'add to cart'}}
        </button>
    </template>

    <script>
        data() {
            return {
                variations: [],
            }
        },
        mounted() {
            this.getVaridations()
        },
        methods: {
            async getVaridations() {         
                try {
                    const variations = await this.$getVatiation.get() // this part is failing and consoling err message from catch
                    this.variations = variations
                } catch (err) {
                    console.log(err) // consoling as TypeError: Cannot read properties of undefined (reading 'get')
                }        
            },
        },
    </script>

这是测试

    describe('Product.vue', () => {
        it('btn display as "Select options" when there is validation', () => {
            const wrapper = mount(Product, {})
            expect(wrapper.find('.product-btn').text()).toBe('Select options') // This passes
        })
    })

您可以模拟任何组件方法,例如

import { shallowMount } from "@vue/test-utils";

 describe('Product.vue', () => {
        it('btn display as "Select options" when there is validation', () => {
            const mocks = {
                $getVatiation: {
                  get: () => [] // returns an empty array, change to what you want to return
                }
            }
            const wrapper = shallowMount (Product, {mocks}) // send your mocks as an argument
            expect(wrapper.find('.product-btn').text()).toBe('Select options') 
        })
    })