如何在 Jest 测试中处理 .gql 文件导入 [英] How to handle .gql file imports in Jest tests

查看:29
本文介绍了如何在 Jest 测试中处理 .gql 文件导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试一个导入 .gql 文件的组件.当我尝试在 Jest 文件中构建组件时,收到此错误:

I'm trying to test a component that imports a .gql file. When I try to build the component in a Jest file, I receive this error:

( object. anonymous function(module exports require __dirname __filename global jest) {
query getUser {                                                
      ˆˆˆˆˆˆˆ
<script>
import GET_USER from 'PATH';
ˆ

有人知道如何忽略导入吗?因为我不需要测试 GraphQL 调用.

Does anyone have any idea of how to ignore the import? Because I don't need to test the GraphQL call.

推荐答案

GraphQL 文档(通常具有 .gql 扩展名)可以直接导入,如果您使用 webpack 并利用随附的加载器graphql-tag.Jest 不适用于开箱即用的 webpack,需要进行配置以处理任何资产文件(如样式表、图像等)的导入.此过程概述 在文档中.

GraphQL documents (which typically have a .gql extension) can be imported directly if you use webpack and utilize the loader that comes with graphql-tag. Jest does not work with webpack out of the box and needs to be configured to handle any imports of asset files like stylesheets, images, etc. This process is outlined in the docs.

根据graphql-tag文档:

不支持 Webpack 的测试环境需要额外配置.对于 Jest,请使用 jest-transform-graphql.

Testing environments that don't support Webpack require additional configuration. For Jest use jest-transform-graphql.

所以你可以使用 jest-transform-graphqlbabel-jest 插件,您可能已经在使用:

So you can utilize jest-transform-graphql along with the babel-jest plugin, which you're probably already using:

"jest": {
  "transform": {
    "\\.(gql|graphql)$": "jest-transform-graphql",
    ".*": "babel-jest"
  }
}

技术上可以通过添加文档中所示的 moduleNameMapper 配置选项来模拟文件,但是,这样做可能会破坏您的组件.

Mocking the file is technically possible by adding the moduleNameMapper config option as shown in the docs, however, doing so is likely to break your components.

这篇关于如何在 Jest 测试中处理 .gql 文件导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆