我正在编写一个 nodeJS 服务,它使用一堆没有 @types 的 npm 模块。
tsc 错误消息告诉我需要添加 index.d.ts 文件,但它没有告诉我将它放在哪里。我的 helper.spec.ts 文件也导入了相同的模块,在使用 jest 运行时也无法检测到 index.d.ts
我将该文件与 tsconfig.json 一起放在我的根目录中,但它没有检测到它。我的文件和结构如下所示:
文件夹结构
node_modules
build
app.js
helper.js
another.js
spec
- helper.spec.ts
- another.spec.ts
src
- app.ts
- helper.ts
- another.ts
tsconfig.json
index.d.ts
jest.config.json
package.json
package-lock.json
Run Code Online (Sandbox Code Playgroud)
配置文件
{
"compilerOptions": {
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"allowJs": true, …Run Code Online (Sandbox Code Playgroud) 我正在使用 Typescript 和 hooks 开发 React 应用程序,并且我正在尝试使用 Enzyme 和 Jest 来测试功能组件。我无法使用 jest.spyOn 来测试组件中的方法。jest.spyOn 方法无法正确解析并在悬停时显示以下消息
“类型''validateBeforeSave”' 的参数不能分配给类型''context' | “setState” | “forceUpdate” | “render” | “componentDidMount” | “shouldComponentUpdate” | “componentWillUnmount” | “componentDidCatch” | “ getSnapshotBeforeUpdate" | ... 还有 6 个 ... | "UNSAFE_componentWillUpdate"'.ts(2345)"
我试图将实例转换为“任何”-
const instance = wrapper.instance() as any;
Run Code Online (Sandbox Code Playgroud)
这当然在编译时忽略了这个问题,但随后测试会抛出一个运行时错误,该函数在组件上不存在。
无法监视 validateBeforeSave 属性,因为它不是函数;给出未定义
// Some function Component
const SomeComponent = (props: IMyComponentProps) => {
const { classes } = props;
// Component has state
const [count, setCount] = useState(0);
function validateBeforeSave(){ …Run Code Online (Sandbox Code Playgroud) 我有一个使用 jest 的 react/typescript 项目,其中有一个自定义匹配器,例如:
export const MyCustomMatchers = {
toBeTheSameAsRemote: function(_util: any, _customEqualityTesters: any) {
return {
compare: function(actual: Brand, expected: RemoteBrand) {
const pass: boolean = attributesMatch(actual, expected);
const message: string = pass
? 'Local matches Remote'
: 'Local does not match Remote';
return { pass, message: () => message };
}
};
}
};
Run Code Online (Sandbox Code Playgroud)
我在我的测试中通过在describe函数内部进行引用:
beforeEach(() => {
jasmine.addMatchers(MyCustomMatchers);
});
Run Code Online (Sandbox Code Playgroud)
并在it函数中像这样使用:
expect(localValue).toBeTheSameAsRemote(remoteValue);
Run Code Online (Sandbox Code Playgroud)
测试运行正常,但打字稿编译器无法识别匹配器,这是有道理的,因为我没有在类型系统中的任何地方定义它
Property 'toBeTheSameAsRemote' does not exist on type 'JestMatchersShape<Matchers<void, MyType[]>, Matchers<Promise<void>, …Run Code Online (Sandbox Code Playgroud) 我有一个函数可以通过 Admin SDK 处理与 Cloud Firestore 的连接。我知道该功能工作正常,因为应用程序连接并允许写入数据库。
现在我正在尝试用 Jest 测试这个功能。为了避免在此函数范围之外进行测试,我模拟了 firebase-admin Node 模块。但是,我的测试失败并出现错误“TypeError:admin.firestore不是函数”。
我的函数和测试都是用 TypeScript 编写的,通过 ts-jest 运行,但我不认为这是 TypeScript 错误,因为 VS Code 没有任何抱怨。我相信这是 Jest 自动模拟的问题。
admin.firebase()是一个有效的调用。TypeScript 定义文件将其定义为function firestore(app?: admin.app.App): admin.firestore.Firestore;
我已经阅读了 Jest 文档,但我不明白如何解决这个问题。
这是我的功能:
// /src/lib/database.ts
import * as admin from "firebase-admin"
/**
* Connect to the database
* @param key - a base64 encoded JSON string of serviceAccountKey.json
* @returns - a Cloud Firestore database connection
*/
export function connectToDatabase(key: string): FirebaseFirestore.Firestore {
// irrelevant code to …Run Code Online (Sandbox Code Playgroud) 我需要在挡板中运行我的测试。我该如何解决这个神秘的问题?
我有一个 nestjs 项目,其中包含多个应用程序和库。当我运行测试时yarn jest --config ./jest.config.json libs/lib1,它运行良好。但是,当我使用 bezel 运行时,bazel test //libs/lib1/...它给了我一个错误“Nest 无法解析依赖项...请确保索引处的参数依赖项...在 RootTestModule 上下文中可用。”。
回购协议
https://github.com/smhmayboudi/bazel_jest_nestjs
Run Code Online (Sandbox Code Playgroud)
我发现 jest.config.json 中的映射顺序很重要。这个效果很好(显示测试+覆盖),但依赖性问题
"moduleNameMapper": {
"@melo/lib1": "<rootDir>/libs/lib1/src",
"@melo/lib1/(.*)": "<rootDir>/libs/lib1/src/$1",
},
Run Code Online (Sandbox Code Playgroud)
这个有效(仅显示传递消息而没有实际测试结果和覆盖率!?)
"moduleNameMapper": {
"@melo/lib1/(.*)": "<rootDir>/libs/lib1/src/$1",
"@melo/lib1": "<rootDir>/libs/lib1/src",
},
Run Code Online (Sandbox Code Playgroud)
玩笑配置
{
"coverageReporters": ["lcov", "text-summary"],
"moduleNameMapper": {
"@melo/libs1": "<rootDir>/libs/libs1/src",
"@melo/libs1/(.*)": "<rootDir>/libs/libs1/src/$1",
},
"modulePathIgnorePatterns": ["/bazel-out/", "/node_modules/"],
"preset": "ts-jest",
"testEnvironment": "node"
}
Run Code Online (Sandbox Code Playgroud)
巴泽尔配置
ts_library(
name = "lib1_test_ts_library",
srcs = glob(["*spec.ts"]),
runtime = "nodejs",
deps = [
":lib1_ts_library",
"@npm//@nestjs/common",
"@npm//@nestjs/testing",
"@npm//@types/jest",
"@npm//rxjs",
"@npm//ts-jest",
], …Run Code Online (Sandbox Code Playgroud) 我使用搜索栏组件构建了一个简单的反应应用程序。搜索栏组件包含一个输入。为了进行测试,我使用 Jest 和 React 测试库。我想编写一个测试,测试当在输入的值中输入某些内容时,输入的占位符是否消失。
Searchbar.test.tsx
test("SearchBar placeholder gets replaced by search string", () => {
const handleSearchRequest = jest.fn();
render(<SearchBar searchInputValue="Hello World"/>);
const searchInput = screen.getByPlaceholderText("Search");
expect(searchInput).toBeFalsy(); //test fails
// expect(searchInput).not.toBeInTheDocument(); //test fails
// expect(searchInput).toBeNull(); //test fails
});
Run Code Online (Sandbox Code Playgroud)
搜索栏.tsx
<Input
placeholder="Search"
value={currentValue}
/>
Run Code Online (Sandbox Code Playgroud)
我应该如何编写这个测试有什么想法吗?
我正在学习 Nestjs 课程,其中有一些单元测试。我编写了这个测试来检查存储库类中的signUp方法。问题是,为了触发异常,该行user.save()应该返回一个承诺拒绝(模拟写入数据库的一些问题)。我尝试了几种方法(见下文),但没有一个有效。
结果是测试成功了,但是有一个unhandled Promise rejection. 这样,即使我断言它not.toThow()会以相同的方式成功unhandled Promise rejection
(node:10149) UnhandledPromiseRejectionWarning: Error: expect(received).rejects.toThrow()
Received promise resolved instead of rejected
Resolved to value: undefined
(Use `node --trace-warnings ...` to show where the warning was created)
Run Code Online (Sandbox Code Playgroud)
我如何让它正确拒绝承诺?
下面是我的测试代码和被测函数。
import { ConflictException } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { UserRepository } from './user.repository';
describe('UserRepository', () => {
let userRepository: UserRepository;
let authCredentialsDto: AuthCredentialsDto …Run Code Online (Sandbox Code Playgroud) 我有这个设置:
// tsconfig.json
{
"compilerOptions": {
"rootDir": "src",
...
}
...
//jest.config.ts
...
globals: {
'ts-jest': {
tsconfig: {
rootDir: '.'
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行 jest 时,我收到一个发出错误,指出打字稿文件需要位于根目录下,似乎这个“rootDir”编译器选项被忽略了。
我不希望我的 /test 或我的配置位于 /src 下,并且我不希望它被编译到 /lib 或被发出。
我也无法排除它,exclude因为这样它也排除了项目外部的 .ts 文件的类型,这使得使用 ts-node 非常困难。
我是测试 React/Typescript 应用程序的新手。我想对我的 React 组件进行单元测试,因为我根本不满足于开发没有测试的应用程序。该应用程序本身运行良好,只是无法在测试模式下运行。
命令(别名react-scripts test):
yarn test
Run Code Online (Sandbox Code Playgroud)
输出:
yarn test
Run Code Online (Sandbox Code Playgroud)
我对@amcharts/amcharts4图书馆有依赖性。虽然Feature页面不使用amCharts,但该库用于其他页面。
Feature页面的简单测试代码:
import * as React from 'react';
import { create } from 'react-test-renderer';
import Feature from "./Feature";
describe('Feature page component', () => {
test('matches the snapshot', () => {
const feature = create(
<Feature />,
);
expect(feature.toJSON()).toMatchSnapshot();
});
});
Run Code Online (Sandbox Code Playgroud)
Feature我的功能性 React 组件 (TSX)在哪里?它是一个由其他组件组成的页面。
在阅读了类似的问题后,我怀疑我的应用程序配置有问题。所以这是我的配置:
.babelrc
{
"presets": ["airbnb"]
}
Run Code Online (Sandbox Code Playgroud)
tsconfig.json:
{
"compilerOptions": {
"target": "esnext",
"jsx": "preserve", …Run Code Online (Sandbox Code Playgroud) 我目前正在使用 jest-preset-Angular 版本 9 在 Angular 9 中设置 Jest,代码运行但出现以下错误:
TypeError: Cannot read property 'ngModule' of null
不知道如何调试。
这是我的 jest.config.json
{
"preset": "jest-preset-angular",
"setupFilesAfterEnv": [
"<rootDir>/setup-jest.ts"
],
"transformIgnorePatterns": [
"node_modules/(?!@ngrx|ngx-socket-io)"
],
"transform": {
"^.+\\.(ts|js|html)$": "ts-jest"
},
"testPathIgnorePatterns": [
"<rootDir>/node_modules/",
"<rootDir>/dist/",
"<rootDir>/src/test.ts"
],
"modulePaths": ["<rootDir>"]
Run Code Online (Sandbox Code Playgroud)
}
和规格文件
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { myComponent } from './knowuser.component';
import 'zone.js';
import 'zone.js/dist/async-test.js';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/zone-testing';
describe('myComponent', () => {
let component: myComponent;
let fixture: ComponentFixture<myComponent>;
beforeEach(async(() => { …Run Code Online (Sandbox Code Playgroud) ts-jest ×10
jestjs ×8
typescript ×6
reactjs ×2
angular ×1
bazel ×1
enzyme ×1
firebase ×1
javascript ×1
nestjs ×1
promise ×1
ts-node ×1
tsc ×1
types ×1
unit-testing ×1