alf*_*aid 14 testing vue.js jestjs
我尝试使用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>
Run Code Online (Sandbox Code Playgroud)
而测试代码是
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();
})
});
})
Run Code Online (Sandbox Code Playgroud)
您还能告诉我什么以及如何使用spyOn来测试该方法吗?
太感谢了
此致
卢格尼
组件定义表明它Form是一个对象。Form.prototype === undefined因为Form不是函数。由于未使用 Vue 类组件,因此没有任何迹象表明相反的情况。
它可以被监视为:
jest.spyOn(Form.methods, 'onSubmit')
Run Code Online (Sandbox Code Playgroud)
这应该在组件实例化之前完成。如果spyOn没有提供任何实现,则会创建一个间谍,而不是一个模拟。
| 归档时间: |
|
| 查看次数: |
83792 次 |
| 最近记录: |