我使用CRA和内置的笑话单元测试库。我用快照编写了一些简单的单元测试,而当测试通过时,我的研究还没有。
当前结果:运行npm test
-通过测试,运行npm run test-coverage
-使用html生成coverage文件夹,但只有React组件不覆盖
预期结果:运行带有快照的React组件npm run test-coverage
时显示覆盖率
package.json
"scripts": {
"test": "react-scripts test --env=jsdom",
"test-coverage": "set CI=true && react-scripts test --coverage --watchAll",
},
"jest": {
"collectCoverageFrom": [
"src/lib/**/*.{js,jsx}",
"!**/node_modules/**",
"!**/coverage/**"
],
"coverageReporters": [
"text",
"html"
],
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": 80
}
}
}
Button.js
export const Button = ({
style,
onClick,
disabled = false,
children,
showSpinner = false,
className
}) => {
return (
<div
style={style}
className={cn('button', className)}
onClick={onClick}
disabled={disabled}
>
{children}
{showSpinner && (
<Spinner className='button--spinner' animation='border' />
)}
</div>
);
};
export default withButton(Button);
Butto.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import { Button } from './Button';
import Icon from '../../Icon';
describe('<Button/> ', () => {
const jsxElement = (
<>
<h1>Hello, world!</h1>Icon <Icon name='doctor' />
</>
);
['string children', <Icon name='doctor' />, jsxElement].forEach(
children => {
it('should render children when it was passed', () => {
const button = renderer.create(<Button>{children}</Button>).toJSON();
expect(button).toMatchSnapshot();
});
}
);
it('should render spinner when showSpinner is true', () => {
const button = renderer.create(<Button showSpinner={true} />).toJSON();
expect(button).toMatchSnapshot();
});
it('should not render spinner by default', () => {
const button = renderer.create(<Button />).toJSON();
expect(button).toMatchSnapshot();
});
});
基于官方文档。它应该工作 https://jestjs.io/docs/en/snapshot-testing#does-code-coverage-work-with-snapshot-testing