gpt4 book ai didi

reactjs - enzyme 设置文件应该写在哪里?

转载 作者:行者123 更新时间:2023-12-03 12:58:00 28 4
gpt4 key购买 nike

昨天我将React项目升级到了v16.0,但是我发现Enzyme有一些问题

    Error: 
Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none. To
configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })`
before using any of Enzyme's top level APIs, where `Adapter` is the adapter
corresponding to the library currently being tested. For example:
import Adapter from 'enzyme-adapter-react-15';
To find out more about this, see http://airbnb.io/enzyme/docs/installation/index.html

at validateAdapter (spec/components/page_components/SongListItem/index.spec.js:9:1141986)
at getAdapter (spec/components/page_components/SongListItem/index.spec.js:9:323041)
at new ReactWrapper (spec/components/page_components/SongListItem/index.spec.js:9:622193)
at mount (spec/components/page_components/SongListItem/index.spec.js:9:2025476)
at UserContext.<anonymous> (spec/components/page_components/SongListItem/index.spec.js:9:1235741)

而且我在官方website上找到了解决方案

// setup file
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

但是我有一个问题: enzyme 的安装文件应该写在哪里?在每个测试文件前面?

我尝试将上述代码添加到其中一个测试文件中,但仍然存在问题

 Internal error: attempt to prepend statements in disallowed (non-array) context at C:/Users/killer/workspace/react/NetEase-Cloud-Music-Web/spec/components/page_components/SongListItem/index.spec.js

This是我项目的地址

最佳答案

我也遇到过类似的问题

如果您使用 jest 来运行测试,您可以创建一个 test-setup.js 文件并添加 enzyme 文档中的代码段:

// test-setup.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

然后在您的 jest 配置中添加一个 setupTestFrameworkScriptFile 键并指向该文件。例如,如果您的 jest 配置位于 package.json 中:

// package.json
{
...,
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>/test-setup.js"
}
}

来自笑话文档 https://facebook.github.io/jest/docs/en/configuration.html#setuptestframeworkscriptfile-string :

The path to a module that runs some code to configure or set up the testing framework before each test. Since setupFiles executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment.

这将在初始化 jest 环境之后、执行 enzyme 测试之前执行

对于使用 create-react-app 的人
您需要运行 yarnjectnpm runject,然后您将在 package.json 中看到 jest 配置。
此外,目前已弃用 setupTestFrameworkScriptFile,取而代之的是 setupFilesAfterEnv

关于reactjs - enzyme 设置文件应该写在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46627353/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com