我经常进行单元测试,我需要比较两个矩对象。我希望我们使用 moment 的内置函数 moment.isSame(moment) 来比较它们。但是,这意味着我的断言将如下所示:
expect(moment1.isSame(moment2)).toBeTrue();
我不太喜欢这个,特别是因为失败消息的信息量会较少。因此,我想编写一个自定义的笑话匹配器“toBeSameMoment”。以下代码似乎至少可以编译:
import moment from "moment";
declare global {
namespace jest {
interface MomentMatchers extends Matchers<moment.Moment> {
toBeSameMoment: (expected: moment.Moment) => CustomMatcherResult;
}
}
}
expect.extend({
toBeSameMoment(received: moment.Moment, expected: moment.Moment): jest.CustomMatcherResult {
const pass: boolean = received.isSame(expected);
const message: () => string = () => pass ? "" : `Received moment (${received.toISOString()}) is not the same as expected (${expected.toISOString()})`;
return {
message,
pass,
};
},
});
Run Code Online (Sandbox Code Playgroud)
但是,我无法真正让它在我的单元测试中工作......当我尝试以下测试代码时:
import moment from "moment";
import "../jest-matchers/moment";
describe("Moment matcher", …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 jest 测试反应打字稿项目,但它给出了一个令人困惑的错误:
这是我的 package.json:
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^12.1.5",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.4.1",
"@types/node": "^16.11.26",
"@types/react": "^17.0.43",
"@types/react-dom": "^17.0.14",
"jest": "^27.5.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.2.2",
"react-scripts": "5.0.0",
"ts-jest": "^27.1.4",
"typescript": "^4.6.3",
"web-vitals": "^2.1.4",
},
"devDependencies": {
"@types/react-test-renderer": "^18.0.0",
"react-test-renderer": "^18.1.0"
}
Run Code Online (Sandbox Code Playgroud)
我写了这个基本测试,它给出了错误:
import renderer from 'react-test-renderer'
import AddShipmentButton from './AddShipmentButton'
it('works', () => {
const tree = renderer.create(<AddShipmentButton />).toJSON()
expect(tree).toMatchSnapshot()
})
Run Code Online (Sandbox Code Playgroud)
我必须使用 --legacy-peer-deps 安装依赖项。可能是什么问题?提前致谢。
配置完成后jest,node.js和typescript脚本npx jest抛出错误控制台
TypeError: Jest: a transform must export something.
at C:\projects\project-api\node_modules\@jest\transform\build\ScriptTransformer.js:386:19
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Promise.all (index 0)
at async ScriptTransformer.loadTransformers (C:\projects\project-api\node_modules\@jest\transform\build\ScriptTransformer.js:378:5)
at async createScriptTransformer (C:\projects\project-api\node_modules\@jest\transform\build\ScriptTransformer.js:1105:3)
at async C:\projects\project-api\node_modules\@jest\core\build\TestScheduler.js:283:31
at async Promise.all (index 0)
at async TestScheduler.scheduleTests (C:\projects\project-api\node_modules\@jest\core\build\TestScheduler.js:276:5)
at async runJest (C:\projects\project-api\node_modules\@jest\core\build\runJest.js:387:19)
at async _run10000 (C:\projects\project-api\node_modules\@jest\core\build\cli\index.js:408:7)
Run Code Online (Sandbox Code Playgroud)
开玩笑的配置文件
export default {
roots: [
'<rootDir>/src'
],
testMatch: [
'**/__tests__/**/*.+(ts)',
'**/?(*.)+(test).+(ts)'
],
transform: {
'^.+\\.(ts)$': 'ts-jest'
}
}
Run Code Online (Sandbox Code Playgroud)
我在哪里没有正确配置它?
几天前我能够运行我的测试并收集它的覆盖范围。(0 , _genMapping.maybeAddMapping) is not a function但是当我今天尝试运行它时,每次测试都会出现错误。仅当我使用覆盖率标志运行时才会发生该错误。
如果我在没有覆盖的情况下跑步,它会按预期工作。
\nPS C:\\projetos> yarn jest\nyarn run v1.22.17\n$ C:\\projetos\\node_modules\\.bin\\jest\n PASS src/shared/utils/__tests__/geralUtils.test.ts (14.834 s)\n PASS src/shared/utils/__tests__/dateUtils.test.ts (15.253 s)\n PASS src/features/motorCalculo/__tests__/motorCalculoUtils.test.ts (5.905 s)\n PASS src/features/motorCalculo/__tests__/motorCalculoParametrosUtils.test.ts (5.19 s)\n PASS src/features/motorCalculo/__tests__/motorCalculoTabelaUtils.test.ts (28.38 s)\n\nTest Suites: 6 passed, 6 total\nTests: 25 passed, 25 total\nSnapshots: 0 total\nTime: 32.256 s\nRan all test suites.\nDone in 40.73s.\nRun Code Online (Sandbox Code Playgroud)\n如果我尝试使用“yarn jest --coverage”或“yarn jest --collectCoverage”收集覆盖率,则会收到以下错误:
\nPS C:\\projetos> yarn jest --collectCoverage\nyarn run v1.22.17\n$ C:\\projetos\\node_modules\\.bin\\jest --collectCoverage\n FAIL src/shared/utils/__tests__/dateUtils.test.ts\n \xe2\x97\x8f Test suite failed to …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 typescript、react-native、expo 和 jest 构建一个移动应用程序。当我尝试运行测试时:
\n FAIL src/components/Button/tests/Button.test.tsx\n \xe2\x97\x8f Test suite failed to run\n\n Cannot find module '@babel/runtime/helpers/interopRequireDefault' from 'node_modules/react-native/jest/setup.js'\n\n at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:324:11)\n at Object.<anonymous> (node_modules/react-native/jest/setup.js:407:30)\nRun Code Online (Sandbox Code Playgroud)\ntsconfig.json
\n{\n "extends": "expo/tsconfig.base",\n "include": ["./src/**/*.ts", "./src/**/*.tsx"],\n "exclude": [\n "node_modules",\n "**/*.spec.ts",\n "**/*.test.ts",\n "**/*.spec.tsx",\n "**/*.test.tsx",\n "jest.config.ts",\n "babel.config.js",\n "metro.config.js",\n "stryker.conf.json"\n ],\n "compilerOptions": {\n "noEmit": true,\n "pretty": true,\n "strict": true,\n "allowJs": true,\n "sourceMap": true,\n "baseUrl": "./src",\n "module": "es2022",\n "target": "ES2021",\n "declaration": true,\n "skipLibCheck": true,\n "jsx": "react-native",\n "esModuleInterop": true,\n "isolatedModules": true,\n "noImplicitReturns": true,\n "resolveJsonModule": true,\n "types": …Run Code Online (Sandbox Code Playgroud) 所以我有一个正在使用的项目:
在我开始编写测试之前,它工作得很好。测试文件位于每个实体文件夹内。例如:
Student
|- Student.ts
|- Student.test.ts
|- StudentService.ts
Run Code Online (Sandbox Code Playgroud)
当我运行 Jest 来执行测试时,一切都很好并且按预期工作。但是,如果我运行,nodemon --exec ts-node src/index.ts我会收到第一个与 Jest 相关的函数的错误,无论是 beforeAll()、afterAll()、describe()...
我的 tsconfig.json 是:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": ["dom", "es6", "es2017", "esnext.asynciterable"],
"sourceMap": true,
"outDir": "./dist",
"moduleResolution": "node",
"types": ["jest", "node"],
"removeComments": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true
},
"include": ["**/*.ts"],
"exclude": ["node_modules", "**/*.test.ts", …Run Code Online (Sandbox Code Playgroud) 我正在使用 Jest 和 Typescript。我有一个不返回任何内容的异步函数(void)。我如何模拟返回 void?我尝试了下面的
const myMockFn = jest.fn().mockImplementationOnce(() => Promise.resolve(void));
jest.mock('../config', () => ({
setup: async () =>
myMockFn(),
}));
Run Code Online (Sandbox Code Playgroud)
但我收到编译错误
Expression expected.
Run Code Online (Sandbox Code Playgroud)
与“Promise.resolve(void)”相关。
我读过许多与我类似的问题,但似乎没有一个能解决我的问题。我正在使用 Vue3、TypeScript、Jest 和 D3 v7。当我尝试时,import * as d3 from "d3";我在测试中收到此错误:
({"Object.<anonymous>":
function(module,exports,require,__dirname,__filename,global,jest)
{export * from "d3-array";
Run Code Online (Sandbox Code Playgroud)
当我这样导入 d3 时也会出现此错误
import { BaseType, Selection, Transition, select } from "d3";
我尝试更新我的笑话配置的transformIgnorePatterns属性以进行读取,但这也不起作用:
transformIgnorePatterns: [
"<rootDir>/node_modules/(?!d3-(array))",
]
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释一下我在这里缺少的部分吗?下面也是我的整个jest.config.js文件
module.exports = {
collectCoverageFrom: [
"**/src/**.ts",
"**/src/**/**.ts",
"!**/dist/**",
"!**/node_modules/**",
"!**/public/**"
],
errorOnDeprecated: true,
preset: "@vue/cli-plugin-unit-jest/presets/typescript",
testMatch: ["**/*.spec.ts", "!**/node_modules/**"],
testPathIgnorePatterns: ["<rootDir>/dist/", "<rootDir>/node_modules/"],
"modulePaths": [
"<rootDir>"
],
transformIgnorePatterns: [
"<rootDir>/node_modules/(?!d3-(array))",
],
transform: {
"^.+\\.ts": "ts-jest",
"^.+\\.vue$": "vue-jest",
},
};
Run Code Online (Sandbox Code Playgroud) 我有依赖于类 A 的类 B。我想测试类 B 的方法,该方法在内部调用类 A 的方法。现在,我想通过模拟类 A 对类 B 的方法进行单元测试。
我的代码结构:
class A {
getSomething() {
return "Something";
}
}
class B {
constructor(objectOfClassA: A) {
this._objectOfClassA = objectOfClassA;
}
functionofClassBToTest() {
const returnValueFromClassA = this._objectOfClassA.getSomething();
return returnValueFromClassA;
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止我已经尝试过:
import ....
import { mocked } from 'jest-mock';
jest.mock("./A", () => {
return {
A: jest.fn().mockImplementation(() => {
return {
getSomething: getSomethingMock
}
})
};
});
const getSomethingMock = jest.fn().mockImplementation(() => {
return "Mock value";
});
const …Run Code Online (Sandbox Code Playgroud) ts-jest ×10
jestjs ×8
typescript ×8
javascript ×2
reactjs ×2
d3.js ×1
matcher ×1
mocking ×1
momentjs ×1
promise ×1
react-native ×1
unit-testing ×1
void ×1
vue.js ×1
vuejs3 ×1