【问题标题】:Unit testing VueJS with axios, TypeScript template, and async functions使用 axios、TypeScript 模板和异步函数对 VueJS 进行单元测试
【发布时间】:2019-04-17 21:41:59
【问题描述】:

我正在尝试对在其mounted() 挂钩中进行 HTTP 调用的组件进行单元测试。我正在使用 CLI 使用 Typescript 和 Jest 创建的模板。我的组件看起来像这样:

export default class UsrUsers extends Vue {
  private error: string = '';
  private users: User[] | null = null;

  private async mounted() {
    const url = process.env.VUE_APP_SERVICE_URL;

    try {
      const res = await axios.get<User[]>(`${url}/api/users`);
      this.users = res.data;

    } catch (ex) {
      this.error = (ex as AxiosError).message;
    }
  }
}

我找到了axios-mock-adapter 包,我有一个这样的测试设置:

describe('Users Container', () => {
  const axiosMock = new MockAdapter(axios);
  const baseUrl = process.env.VUE_APP_SERVICE_URL;

  it('should display no user when user list is empty', async () => {
    axiosMock.onGet(`${baseUrl}/api/users`).reply(200, []);

    const wrapper = await shallowMount(UsrUsers);
    expect(wrapper.text()).toMatch('no user');
  });
});

但是,它不起作用(我也尝试使用jest.mock('axios')),我得到一个空字符串wrapper.text()

我也尝试过像这样使用$nextTick

it('should display no user', done => {
  // Set up axiosMock
  const wrapper = shallowMount(UsrUsers);

  wrapper.vm.$nextTick(() => {
    expect(wrapper.text()).toMatch('no user');
    done();
  });
});

但是消息Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout会超时

那么,我怎样才能正确地测试这个组件呢?我试图在互联网上找到一些东西,但没有找到任何东西。

【问题讨论】:

    标签: typescript vuejs2 axios jestjs vue-test-utils


    【解决方案1】:

    您没有使用 axios mock 回复 200 上的任何内容。 axiosMock.onGet('${baseUrl}/api/users').reply(200, []); 应该是 axiosMock.onGet('${baseUrl}/api/users').reply(200, {data: 'no user'}); 或类似的东西。但是您必须回复一些数据,以便您的组件使用它来更新自己,就像在您的示例中一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-07
      • 2021-09-25
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      • 2016-02-21
      相关资源
      最近更新 更多