Commit 88f8802b authored by 梁柱's avatar 梁柱

初始化jest

parents
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[Makefile]
indent_style = tab
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/npm-debug.log*
/yarn-error.log
/yarn.lock
/package-lock.json
# production
/dist
# misc
.DS_Store
# umi
/src/.umi
/src/.umi-production
/src/.umi-test
/.env.local
**/*.md
**/*.svg
**/*.ejs
**/*.html
package.json
.umi
.umi-production
.umi-test
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"overrides": [
{
"files": ".prettierrc",
"options": { "parser": "json" }
}
]
}
import { defineConfig } from 'umi';
import path from 'path';
export default defineConfig({
nodeModulesTransform: {
type: 'none',
},
routes: [
{ path: '/', component: '@/pages/index' },
{ exact: true, path: '/user', component: '@/pages/user' },
{ component: '@/pages/404' },
],
fastRefresh: {},
alias: {
'@': path.resolve(__dirname, './src')
},
});
# umi project
## Getting Started
Install dependencies,
```bash
$ yarn
```
Start the dev server,
```bash
$ yarn start
```
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/en/configuration.html
*/
export default {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\Lenovo\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: [
'src/**/*.{js,jsx,ts,tsx}',
'!**/typings/**',
'!**/types/**',
'!**/fixtures/**',
'!**/examples/**',
'!**/*.d.ts',
],
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: [
'\\\\node_modules\\\\',
'.umi',
'.umi-production',
'demos',
],
// Indicates which provider should be used to instrument code for coverage
// coverageProvider: "babel",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx'],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
moduleNameMapper: {
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
'^@/(.*)$': '<rootDir>/src/$1',
'^@@/(.*)$': '<rootDir>/src/.umi/$1',
axios: 'axios/dist/node/axios.cjs',
},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
roots: ['<rootDir>/src'],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
setupFiles: [require.resolve('@umijs/test/helpers/setupFiles/shim')],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
setupFilesAfterEnv: [
require.resolve('@umijs/test/helpers/setupFiles/jasmine'),
],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: require.resolve('jest-environment-jsdom-fourteen'),
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
testMatch: [
'<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}',
'<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}',
],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
testPathIgnorePatterns: ['\\\\node_modules\\\\'],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jasmine2",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
transform: {
'^.+.(js|jsx|ts|tsx)$': require.resolve(
'@umijs/test/helpers/transformers/javascript',
),
'^.+.(css|less|sass|scss|stylus)$': require.resolve(
'@umijs/test/helpers/transformers/css',
),
'^(?!.*.(js|jsx|ts|tsx|css|less|sass|scss|stylus|json)$)': require.resolve(
'@umijs/test/helpers/transformers/file',
),
},
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
transformIgnorePatterns: [
'[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$',
'^.+\\.module\\.(css|sass|scss)$',
'node_modules/(?!axios)',
],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
export default {
'GET /api/test': { name: 'foo' }
}
\ No newline at end of file
{
"private": true,
"scripts": {
"start": "umi dev",
"build": "umi build",
"postinstall": "umi generate tmp",
"prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'",
"test": "jest --watchAll",
"test:coverage": "jest --coverage"
},
"gitHooks": {
"pre-commit": "lint-staged"
},
"lint-staged": {
"*.{js,jsx,less,md,json}": [
"prettier --write"
],
"*.ts?(x)": [
"prettier --parser=typescript --write"
]
},
"dependencies": {
"@ant-design/pro-layout": "^6.5.0",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "12.1.5",
"@types/jest": "^29.4.0",
"axios": "^1.3.4",
"react": "17.x",
"react-dom": "17.x",
"umi": "^3.5.36"
},
"devDependencies": {
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"@umijs/preset-react": "1.x",
"@umijs/test": "^3.5.36",
"identity-obj-proxy": "^3.0.0",
"jest-environment-jsdom-fourteen": "^1.0.1",
"lint-staged": "^10.0.7",
"prettier": "^2.2.0",
"ts-node": "^10.9.1",
"typescript": "^4.1.2",
"yorkie": "^2.0.0"
}
}
import styles from './index.less';
export default function IndexPage() {
return (
<div>
<h1 className={styles.title}>404</h1>
</div>
);
}
.title {
background: rgb(121, 242, 157);
}
import Todolist from './todolist'
export default function IndexPage() {
return (
<Todolist></Todolist>
);
}
.head {
display: flex;
}
import { render, screen, fireEvent } from '@testing-library/react';
import React from 'react';
import '@testing-library/jest-dom';
import Todolist from '.';
it(`
1. 输入内容
2. 点击添加
3. 展示list
`, async () => {
// 渲染组件
render(<Todolist />);
await fireEvent.change(screen.getByRole('input'), {
target: { value: '学习Jest' },
});
await fireEvent.click(screen.getByRole('button'));
expect(screen.getByText(/学习Jest/i)).toBeInTheDocument();
await fireEvent.change(screen.getByRole('input'), {
target: { value: '学习Jest2' },
});
await fireEvent.click(screen.getByRole('button'));
expect(screen.getByText(/学习Jest2/i)).toBeInTheDocument();
expect(screen.getAllByRole('listItem').length).toBe(2);
});
import React, { useState } from 'react';
import { Button, Input } from 'antd';
import styles from './index.less';
// import User from '@/pages/user';
interface InputChangeEvent extends React.ChangeEvent<HTMLInputElement> {}
export default function IndexPage() {
const [value, setValue] = useState<string>('');
const [list, setList] = useState<string[]>([]);
const onChange = (e: InputChangeEvent): void => {
setValue(e.target.value);
};
const addItem = (): void => {
if (value) {
const newList = [...list, value];
setList(newList);
setValue('');
}
};
return (
<>
<div className={styles.head}>
<Input type="text" value={value} onChange={onChange} role="input" />
<Button type="primary" onClick={addItem} role="button">
添加
</Button>
</div>
<div className="list">
{list.map((item, index) => (
<div className="listItem" key={index} role="listItem">
{item}
</div>
))}
</div>
{/* <User></User> */}
</>
);
}
.title {
background: rgb(121, 242, 157);
}
import styles from './index.less';
import React, { useState } from 'react';
interface InputElement extends React.ChangeEvent<InputElement> {}
export default function IndexPage() {
const [value, setValue] = useState(0);
const onChange = (): void => {
console.log(value + 1);
setValue(value + 1);
};
return (
<div>
<h1 className={styles.title}>Page user{value}</h1>
<button onClick={onChange}>加一</button>
</div>
);
}
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`测试快照 config 1`] = `
Object {
"hot": true,
"port": 80,
"server": "123",
}
`;
import { config } from '../config';
it('测试快照 config ', () => {
expect(config()).toMatchSnapshot();
});
import { add, fetchData, returnCallBack, timerCallBack } from '../demo';
it('测试加法: 2+ 2 = 4', () => {
expect(add(2, 2)).toBe(4);
});
// it('测试fetchData', async () => {
// await expect(fetchData()).resolves.toMatchObject({
// data: {
// name: 'foo'
// }
// })
// });
it('测试returnCallBack', async () => {
const func = jest.fn();
returnCallBack(func);
expect(func).toBeCalled();
expect(func.mock.calls.length).toBe(1);
const mockFn = jest.fn();
mockFn.mockImplementation(() => 36);
returnCallBack(mockFn);
expect(mockFn.mock.results[0].value).toEqual(36)
});
jest.useFakeTimers();
it('timerCallBack', async () => {
const func = jest.fn();
timerCallBack(func);
jest.advanceTimersByTime(3000);
expect(func).toHaveBeenCalledTimes(1);
});
\ No newline at end of file
export const config = () => {
return {
port: 80,
hot: true,
server: '123'
}
}
\ No newline at end of file
import axios from "axios";
function add(a: number, b: number): number {
return a + b;
}
function fetchData() {
return axios('http://localhost:8000/api/test');
}
function returnCallBack(fn: Function) {
fn();
}
function timerCallBack(fn:Function){
setTimeout(()=>{
fn()
},3000);
}
export {
add,
fetchData,
returnCallBack,
timerCallBack
}
\ No newline at end of file
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"importHelpers": true,
"jsx": "react-jsx",
"esModuleInterop": true,
"sourceMap": true,
"baseUrl": "./",
"strict": true,
"paths": {
"@/*": ["src/*"],
"@@/*": ["src/.umi/*"]
},
"allowSyntheticDefaultImports": true
},
"include": [
"mock/**/*",
"src/**/*",
"config/**/*",
".umirc.ts",
"typings.d.ts"
],
"exclude": [
"node_modules",
"lib",
"es",
"dist",
"typings",
"**/__test__",
"test",
"docs",
"tests"
]
}
declare module '*.css';
declare module '*.less';
declare module '*.png';
declare module '*.svg' {
export function ReactComponent(
props: React.SVGProps<SVGSVGElement>,
): React.ReactElement;
const url: string;
export default url;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment