按道理说官配用起来会更舒服才是,结果接连碰壁,加上雷同状况的资料确实有点少,只能填一下。css
首先脚手架确定不是cra
(cra
用户请直接用官方封装的测试就行),咱们确定会使用本身定制的脚手架。当咱们在选用Jest
作单测时,出现了几个问题:html
typescript
webpack
css-modules
第二点简直硬伤,直接致使第三点无从下手。而鄙人又出于“不敢乱动祖传代码”的原则,只能往上面继续填。react
由你喜欢的方式去安装 Jest
webpack
npm i -D jest @types/jest #or yarn
复制代码
接着须要配置启动方式git
// package.json
{
...
"scripts": {
"test": "jest",
...
}
...
"jest": {}
}
复制代码
还有一个方法官方并无说起到(或者我没有注意到)的方法,在你的project
放置一个jest.config.js
,一样能够配置,对package.json
有洁癖的同窗适用。github
-- 首先咱们须要什么?
-- TypeScript
!web
npm i -D ts-jest #由于咱们已经用上了 TypeScript 因此不须要多装一次
复制代码
{
"jest": {
"moduleFileExtensions": [
"ts",
"tsx"
],
"transform": {
"^.+\\.tsx?$": "ts-jest",
}
}
}
复制代码
接着,虽然把每一个组件的单测放在该组件的文件夹中显得更清晰(cra
的作法),可是咱们会更愿意把全部测试用例放在test
文件夹中。因此创建好test
目录,继续加配置typescript
{
"jest": {
"moduleFileExtensions": [
"ts",
"tsx"
],
"transform": {
"^.+\\.tsx?$": "ts-jest",
},
"testMatch": [
"<rootDir>/test/**/?(*.)(spec|test).ts?(x)"
],
}
}
复制代码
这样,在相似ydjnb.test.tsx
或者ydjnb.spec.ts
等等等等的文件才会被捕获为测试文件进行测试。npm
// ydjnb.spec.ts
test('Jest-TypeScript 尝试运行', () => {
expect(1+1).toBe(2) // Pass
})
复制代码
至此,你可使用对Typescript
的测试,但对于React
来讲还差一点。json
这里咱们就直接选用Enzyme
了,在Jest
文档,关于Testing React Apps -- DOM Testing
中,也提到是建议使用Enzyme
。
npm i -D enzyme @types/enzyme
复制代码
回到ydjnb.spec.ts
中,如今由于涉及到JSX
因此应该更名为*.tsx
了
// ydjnb.spec.tsx
import { shallow } from 'enzyme'
test('Jest-React-TypeScript 尝试运行', () => {
const renderer = shallow(<div>hello world</div>)
expect(renderer.text()).toEqual('hello world')
})
复制代码
固然shallow
只是一种“浅渲染”,它只会对当前组件渲染,作断言。通常测试除了关心数据还会关心交互,因此还会有另外两个方法render
, mount
。
-- 配完了!运行一下吧!
-- ERROR
其实细心一点就会发现,我上面的代码段并无标记// Pass
,并且如今你可能还回头看了!
因此第一个错误仍是很好解决的,由于你仔细看一下测试结果,Enzyme
已经告诉你了。
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, whereAdapter
is the adaptercorresponding 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
不过我知道我用的已是react-16
了,跟着文档也会提到关于react-16
的解决方法。
npm i -D enzyme-adapter-react-16
复制代码
回到ydjnb.spec.tsx
中,
// ydjnb.spec.tsx
import { shallow, configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })
test('Jest-React-TypeScript 尝试运行', () => {
const renderer = shallow(<div>hello world</div>)
expect(renderer.text()).toEqual('hello world') // Pass
})
复制代码
根据Jest
的文档,加上一个库解决问题:identity-obj-proxy
{
"moduleNameMapper": {
"\\.(css|scss)$": "identity-obj-proxy"
},
"transform": {
...
},
...
}
复制代码
至此,需求已经能彻底运做。