微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Mocha 测试 Vue GraphQl 客户端组件时出错

如何解决使用 Mocha 测试 Vue GraphQl 客户端组件时出错

我正在尝试测试一个使用 GraphQL 获取数据的 vue 组件。我正在使用 Mocha 和 Chai。

import { expect } from 'chai'
import { mount } from '@vue/test-utils'
import OutlierFetcher from '@/components/OutlierFetcher.vue'

describe('OutlierFetcher.vue',() => {
  it('renders h1 tag',() => {
    const wrapper = mount(OutlierFetcher);
    expect(
      wrapper
        .find("h1")
        .text() == "Helloworld"
    );
  })
})

当我尝试运行 npm run test:unit 时。我收到此错误

    Invariant Violation: 
    "fetch" has not been found globally and no fetcher has been configured. 
    To fix this,install a fetch package (like 
    https://www.npmjs.com/package/cross-fetch),instantiate the fetcher,and 
    pass it into your HttpLink constructor. For example:

import fetch from 'cross-fetch';
import { ApolloClient,HttpLink } from '@apollo/client';
const client = new ApolloClient({
  link: new HttpLink({ uri: '/graphql',fetch })
});

vue组件的graphql查询设置如下图:

const defaultClient = new ApolloClient({
  uri: 'http://localhost:8081/query',cache: new InMemoryCache()
})

const query = gql `query outliers($dataId: String!) {
                      outliers(dataId: $dataId) {
                        Data
                      }
                   }`
                   
fetchOutliers() {
      this.loading = true;
      defaultClient.cache.reset();
      defaultClient.query({ query: query,variables: { dataId: this.dataname}
                         }).then(res =>       this.updateOutliers(res.data.outliers)); 
    },

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。