【问题标题】:Cannot spyOn on a primitive value; undefined given . Vue JS, Jest, Utils无法窥探原始值;未定义给定。 Vue JS、Jest、Utils
【发布时间】:2020-12-06 13:35:28
【问题描述】:

我尝试使用 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 来测试方法吗?

非常感谢

最好的问候

鲁格尼

【问题讨论】:

    标签: vue.js testing jestjs


    【解决方案1】:

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

    它可以被窥探为:

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

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

    【讨论】:

    • 如果有帮助,我遇到了不得不写jest.spyOn(Form.options.methods, 'onSubmit') 的情况。这可能是由于组件编写语法的原因,但我尚未深入研究
    猜你喜欢
    • 2021-11-02
    • 2020-10-30
    • 2020-02-24
    • 2020-08-08
    • 2021-07-05
    • 2017-02-27
    • 2020-06-11
    • 1970-01-01
    • 2019-03-07
    相关资源
    最近更新 更多