我正在尝试为 VueJS 组件编写我的第一个单元测试,该组件在呈现时从 API 端点获取一些数据:

我的 VueJS 组件:

import axios from 'axios';

export default {
  props: {
          userIndexUrl: {
            required: true
          }
        },
  data() {
    userList: [],
    tableIsLoading: true
  },
  created() {
    const url = this.userIndexUrl;
    axios.get(url)
    .then(response => {
      this.userList = response.data.data;
      this.tableIsLoading = false;
    })
  },
}

和我的测试:
import { mount } from 'vue-test-utils'
import moxios from 'moxios'
import UsersAddRemove from 'users_add_remove.vue'

describe('UsersAddRemove', () => {
  const PROPS_DATA = {
      userIndexUrl: '/users.json'
  }

  beforeEach(() => {
    moxios.install();
    moxios.stubRequest('/users1.json', {
      status: 200,
      response: {
        "count": 1,
        "data": [
            { "id" : 1,
              "email" : "[email protected]",
              "first_name" : "Kenneth",
              "last_name" : "Connelly"
            }
          ]
        }
    });
  });

  afterEach(() => {
    moxios.uninstall();
  });

  it('loads users from remote JSON endpoint and renders table', () => {
    const wrapper = mount(UsersAddRemove, { propsData: PROPS_DATA });
    moxios.wait(() => {
      expect(wrapper.html()).toContain('<td class="">[email protected]</td>');
      done();
    });
  });
});

所以我期望发生的是组件被实例化,然后它执行一个 API 调用,它被 Moxios 捕获,之后它应该执行 moxios.wait ,这没有发生。测试似乎忽略了 moxios.wait ,即使它不应该成功通过。

我在这里缺少什么?

最佳答案

尝试添加 done 作为参数:

  it('loads users from remote JSON endpoint and renders table', (done) => {
  // -----------------------------------------------------------^^^^^^
    const wrapper = mount(UsersAddRemove, { propsData: PROPS_DATA });
    moxios.wait(() => {
      expect(wrapper.html()).toContain('<td class="">[email protected]</td>');
      done();
    });
  });

等待 Ajax

更改如下:
// remove the stubRequest of beforeEach()
beforeEach(() => {
  moxios.install();
});

// afterEach stays the same

it('loads users from remote JSON endpoint and renders table', (done) => {
  const wrapper = mount(UsersAddRemove, { propsData: PROPS_DATA });

  moxios.wait(() => {
    let request = moxios.requests.mostRecent();
    request.respondWith({
      status: 200,
      response: {
        "count": 1,
        "data": [{
          "id": 1,
          "email": "[email protected]",
          "first_name": "Kenneth",
          "last_name": "Connelly"
        }]
      }
    }).then(function() {
      expect(wrapper.html()).toContain('<td class="">[email protected]</td>');
      done();
    });
  });
});

关于vue.js - `moxios.wait` 在使用 Jest、Vue Test Utils 和 Moxios 测试 VueJS 时从不执行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49130579/

10-10 22:11