首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用MDX和graphql数据测试Gatsby组件

用MDX和graphql数据测试Gatsby组件
EN

Stack Overflow用户
提问于 2020-12-07 15:22:21
回答 1查看 553关注 0票数 4

我试图在Jest中为组件'Step.js‘编写一个单元测试,它用作使用GraphQL数据动态创建页面的模板。我在测试中提供了假数据,希望它能够通过GraphQL查询解决。但我得到的错误消息是:“语法错误:不能在模块外使用导入语句”。

从那以后,我试过:

  1. 在文件中添加了一个“静态查询”模拟,希望这将在测试环境中生成假数据。但是我在‘message.
  2. Adding’配置选项中得到了相同的错误moduleNameMapper 'mdx‘。我仍然收到了同样的错误消息。我的下一个尝试可能是安装‘Jest-转换器-mdx’,看看是否可以将它添加到'jest.config.js'.

中。

我只是想知道是否有任何关于这个问题的建议?或者以前有人遇到过这种情况吗?如果你有什么建议,请分享!提前感谢

这是密码,

Step.js

代码语言:javascript
复制
import React from "react"
import { graphql } from "gatsby"
import { MDXRenderer } from "gatsby-plugin-mdx"
import Layout from "./layout"
import style from "./step.module.css"

export default function Step({ data }) {
  const mdx = data.mdx
  return (
    <div>
      <h1 className={style.title}>{mdx.frontmatter.title}</h1>
      <Layout>
        <MDXRenderer>{mdx.body}</MDXRenderer>
      </Layout>
    </div>
 )
}

export const query = graphql`
  query($slug: String!) {
    mdx(fields: { slug: { eq: $slug } }) {
      body
      frontmatter {
        title
      }
    }
  }
`

Step.test.js

代码语言:javascript
复制
import React from "react"
import renderer from "react-test-renderer"
import { StaticQuery } from "gatsby"
import Step from "../src/components/step"

beforeEach(() => {
  StaticQuery.mockImplementationOnce(({ render }) => {
    render({
        mdx: {
          body: "function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsxRuntime classic */\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Homebrew\"\n};\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"p\", null, \"It's important to keep your programs up to date, to check to see if anything is outdated, you can use this command:\"), mdx(CommandBox, {\n    mdxType: \"CommandBox\"\n  }, \"brew outdated\"), mdx(\"p\", null, \"And to update:\"), mdx(CommandBox, {\n    mdxType: \"CommandBox\"\n  }, \"brew update\"), mdx(\"p\", null, \"If anything has gone wrong with your installation or update, you can uninstall Homebrew and start again:\"), mdx(CommandBox, {\n    mdxType: \"CommandBox\"\n  }, \"/bin/bash -c \\\"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)\\\"\"), mdx(StepButton, {\n    to: \"/step-4\",\n    mdxType: \"StepButton\"\n  }));\n}\n;\nMDXContent.isMDXComponent = true;",
          frontmatter: {
            title: "Homebrew"
          },
        },
    })
  })
})


describe("Step component", () => {
  it("render step content on the page", () => {
    const data = {
        mdx: {
          body: "function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsxRuntime classic */\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Homebrew\"\n};\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"p\", null, \"It's important to keep your programs up to date, to check to see if anything is outdated, you can use this command:\"), mdx(CommandBox, {\n    mdxType: \"CommandBox\"\n  }, \"brew outdated\"), mdx(\"p\", null, \"And to update:\"), mdx(CommandBox, {\n    mdxType: \"CommandBox\"\n  }, \"brew update\"), mdx(\"p\", null, \"If anything has gone wrong with your installation or update, you can uninstall Homebrew and start again:\"), mdx(CommandBox, {\n    mdxType: \"CommandBox\"\n  }, \"/bin/bash -c \\\"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)\\\"\"), mdx(StepButton, {\n    to: \"/step-4\",\n    mdxType: \"StepButton\"\n  }));\n}\n;\nMDXContent.isMDXComponent = true;",
          frontmatter: {
            title: "Homebrew"
          },
        },
    }

    const tree = renderer.create(<Step data={data}/>).toJSON()
    expect(tree).toMatchSnapshot()
  });
});

jest.config.js

代码语言:javascript
复制
module.exports = {
  transform: {
    "^.+\\.jsx?$": `<rootDir>/jest-preprocess.js`,
  },
  moduleNameMapper: {
    ".+\\.(css|styl|less|sass|scss)$": `identity-obj-proxy`,
    ".+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": `<rootDir>/__mocks__/file-mock.js`,
  },
  testPathIgnorePatterns: [`node_modules`, `\\.cache`, `<rootDir>.*/public`],
  transformIgnorePatterns: [`node_modules/(?!(gatsby)/)`],
  globals: {
    __PATH_PREFIX__: ``,
  },
  testURL: `http://localhost`,
  setupFiles: [`<rootDir>/loadershim.js`],
}
EN

回答 1

Stack Overflow用户

发布于 2020-12-11 12:36:25

经过一些帮助,我终于通过了考试。看起来Jest很难找到‘’模块,以及它的'MDXRenderer‘模块。于是我嘲笑了他们,并归还了传入的“孩子”。

代码语言:javascript
复制
import React from "react"
import renderer from "react-test-renderer"
import { StaticQuery } from "gatsby"
import Step from "../src/components/step"


jest.mock("gatsby-plugin-mdx", () => {
  return { MDXRenderer: ({children}) => {
    return <div>{children}</div>;
  } }
});

beforeEach(() => {
  StaticQuery.mockImplementationOnce(({ render }) => {
    render({
        mdx: {
          body: "function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsxRuntime classic */\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Homebrew\"\n};\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"p\", null, \"It's important to keep your programs up to date, to check to see if anything is outdated, you can use this command:\"), mdx(CommandBox, {\n    mdxType: \"CommandBox\"\n  }, \"brew outdated\"), mdx(\"p\", null, \"And to update:\"), mdx(CommandBox, {\n    mdxType: \"CommandBox\"\n  }, \"brew update\"), mdx(\"p\", null, \"If anything has gone wrong with your installation or update, you can uninstall Homebrew and start again:\"), mdx(CommandBox, {\n    mdxType: \"CommandBox\"\n  }, \"/bin/bash -c \\\"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)\\\"\"), mdx(StepButton, {\n    to: \"/step-4\",\n    mdxType: \"StepButton\"\n  }));\n}\n;\nMDXContent.isMDXComponent = true;",
          frontmatter: {
            title: "Homebrew"
          },
        },
    })
  })
})


describe("Step component", () => {
  it("render step content on the page", () => {
    const data = {
        mdx: {
          body: "function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsxRuntime classic */\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Homebrew\"\n};\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"p\", null, \"It's important to keep your programs up to date, to check to see if anything is outdated, you can use this command:\"), mdx(CommandBox, {\n    mdxType: \"CommandBox\"\n  }, \"brew outdated\"), mdx(\"p\", null, \"And to update:\"), mdx(CommandBox, {\n    mdxType: \"CommandBox\"\n  }, \"brew update\"), mdx(\"p\", null, \"If anything has gone wrong with your installation or update, you can uninstall Homebrew and start again:\"), mdx(CommandBox, {\n    mdxType: \"CommandBox\"\n  }, \"/bin/bash -c \\\"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)\\\"\"), mdx(StepButton, {\n    to: \"/step-4\",\n    mdxType: \"StepButton\"\n  }));\n}\n;\nMDXContent.isMDXComponent = true;",
          frontmatter: {
            title: "Homebrew"
          },
        },
    }

    const tree = renderer.create(<Step data={data}/>).toJSON()
    expect(tree).toMatchSnapshot()
  });
});

如果任何人有任何反馈或发现任何其他东西,请告诉我。谢谢!

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65184456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档