无法监视基元值;给定未定义 .Vue JS, Jest, Utils.



我尝试使用spyOn来监视函数及其实现。但是,我得到了这个错误。"不能监视原始值;未定义给定"。

我已经在 https://jestjs.io/docs/en/jest-object 中阅读了 jest.spyOn 的文档。但它一直表现出同样的错误...有什么需要补充和改进的吗?

下面是代码

<template>
<div>
<form @submit.prevent="onSubmit(inputValue)">
<input type="text" v-model="inputValue">
<span class="reversed">{{ reversedInput }}</span>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
props: ['reversed'],
data: () => ({
inputValue: '',
results: [],
}),
methods: {
onSubmit(value) {
const getPromise = axios.get(
'https://jsonplaceholder.typicode.com/posts?q=' + value,
);
getPromise.then(results => {
this.results = results.data;
});
return getPromise;
},
},
};
</script>

而测试代码是

import axios from 'axios'; // axios here is the mock from above!
import { shallowMount } from '@vue/test-utils';

import Form from '@/components/Form.vue';
describe('Form.test.js', () => {
const wrapper;
describe('Testing Submit events', () => {
wrapper = shallowMount(Form);

it('calls submit event', () => {
const onSubmit = jest.spyOn(Form.prototype, 'onSubmit') // mock function

// updating method with mock function
wrapper.setMethods({ onSubmit });

//find the button and trigger click event
wrapper.findAll('form').trigger('submit');
expect(onSubmit).toBeCalled();
})

});
})

您能否也为我提供什么以及如何使用spyOn来测试该方法?

非常感谢

此致敬意

卢格尼

组件定义表明Form是一个对象。Form.prototype === undefined因为Form不是一个函数。由于 Vue 类组件没有被使用,所以没有什么迹象表明相反。

它可以被监视为:

jest.spyOn(Form.methods, 'onSubmit')

这应该在组件实例化之前完成。没有提供实现spyOn会创建间谍,而不是模拟。

我遇到了类似的问题,解决方案令人震惊。 导入并使用mount而不是shallowMountwrapper,为我修复了它。

我能够通过将初始化放在 beforeEach 块中来解决代码中的此错误。尝试:

import axios from 'axios'; // axios here is the mock from above!
import { shallowMount } from '@vue/test-utils';

import Form from '@/components/Form.vue';
describe('Form.test.js', () => {
describe('Testing Submit events', () => {
const wrapper;
beforeEach(() => {
wrapper = shallowMount(Form);
} );
it('calls submit event', () => {
const onSubmit = jest.spyOn(Form.prototype, 'onSubmit') // mock function

// updating method with mock function
wrapper.setMethods({ onSubmit });

//find the button and trigger click event
wrapper.findAll('form').trigger('submit');
expect(onSubmit).toBeCalled();
})

});
})

最新更新