【问题标题】:How to mock VueAxios in jest如何开玩笑地模拟 VueAxios
【发布时间】:2020-11-18 20:25:16
【问题描述】:

我想测试我的 Api 函数,它们位于 vue 组件之外的单独文件中。在这个方法中,我通过 Vue.axios 调用 api,但我找不到像这篇文章中那样模拟和测试它的方法:

How do I test axios in jest

示例方法:

cancelAuction: function (auction_id) {
    if (validateApiInt(auction_id)) {
      return Vue.axios.delete(`/auctions/${auction_id}`);
    }
    return {};
  },

示例用法:

const response = await AuctionApi.cancelAuction(id);

【问题讨论】:

    标签: vue.js testing jestjs axios


    【解决方案1】:

    好的,这很明显。我不得不像下面这样模拟整个 Vue:

    jest.mock('vue', () => ({
      axios: {
        get: jest.fn()
      },
    }));
    

    【讨论】:

      【解决方案2】:

      刚开始学习 Jest + @vue/test-utils。对于那些想要模拟“vue-axios”的人来说,这是一个简单的例子。

      // @/components/Helloword.vue
      
      <template>
        <div>
          <h1>Email: <span>{{ email }}</span></h1>
          <button @click="fetchData">Get Random Email</button>
        </div>
      </template>
      
      <script>
      export default {
        name: 'HelloWorld',
        data() {
          return {
            email: '',
          };
        },
        methods: {
          async fetchData() {
            const res = (await this.axios.get('https://randomuser.me/api/')).data
              .results[0].email;
            this.email = res;
          },
        },
      };
      </script>
      

      --

          // test/unit/example.spec.js
      
      import { mount } from '@vue/test-utils';
      import HelloWorld from '@/components/HelloWorld.vue';
      import axios from 'axios';
      
      jest.mock('axios', () => ({
        get: () =>
          Promise.resolve({
            data: {
              results: [{ email: 'mockAxios@email.com' }],
            },
          }),
      }));
      
      describe('HelloWorld.vue', () => {
        it('click and fetch data...', async (done) => {
          const wrapper = mount(HelloWorld, {
            mocks: {
              axios,
            },
          });
      
          await wrapper.find('button').trigger('click');
      
          wrapper.vm.$nextTick(() => {
            expect(wrapper.find('h1').text()).toContain('@');
            done();
          });
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-01
        • 1970-01-01
        • 2020-08-20
        • 2021-05-27
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2018-07-25
        相关资源
        最近更新 更多