4

我正在尝试为 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" : "brayan@schaeferkshlerin.net",
              "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="">brayan@schaeferkshlerin1.net</td>');
      done();
    });
  });
});

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

我在这里想念什么?

4

1 回答 1

7

尝试添加doneas 参数:

  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="">brayan@schaeferkshlerin1.net</td>');
      done();
    });
  });

等待阿贾克斯

更改如下:

// 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": "brayan@schaeferkshlerin.net",
          "first_name": "Kenneth",
          "last_name": "Connelly"
        }]
      }
    }).then(function() {
      expect(wrapper.html()).toContain('<td class="">brayan@schaeferkshlerin1.net</td>');
      done();
    });
  });
});
于 2018-03-06T12:15:33.257 回答