标签: ts-jest

TypeScript 装饰器的意外标记

我想测试一些使用 TypeScript 5.0 中新添加的装饰器(不是实验装饰器)的代码,如何让 Jest 解释该代码?

SyntaxError: Invalid or unexpected token当它遇到一个时我得到@

我的jest.config.js样子是这样的

module.exports = {
  preset: 'ts-jest',
  transform: {
    '^.+\\.(ts|tsx)?$': ['ts-jest', {
      tsConfig: 'tsconfig.esm.json'
    }],
    "^.+\\.(js|jsx)$": "babel-jest",
  }
};
Run Code Online (Sandbox Code Playgroud)

tsconfig.esm.json

{
  "compilerOptions": {
    "module": "esnext",
    "target": "esnext",
    "outDir": "dist/esm",
    "declaration": true,
    "declarationMap": true,
    "declarationDir": "dist/types",
    "sourceMap": true,
    "strict": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "nodenext",
    "baseUrl": ".",
    "paths": {
      "*": ["src/*"]
    }
  },
  "include": ["src/*.ts","src/**/*.ts", "test/*.ts"],
  "exclude": ["node_modules"]
}
Run Code Online (Sandbox Code Playgroud)

babel.config.js

module.exports = {presets: ['@babel/preset-env']}
Run Code Online (Sandbox Code Playgroud)

typescript jestjs babel-jest ts-jest

5
推荐指数
1
解决办法
595
查看次数

如何在笑话中获取新行覆盖率(不是整个文件%)

我一直在使用 jest --coverage 来计算我的代码的覆盖率。我coverageThreshold在 jest.config.js 中添加了一个,但这仅检查整个代码库/文件夹覆盖范围。

我也尝试过开玩笑-o--onlyChanged),但这会生成整个文件的覆盖百分比,使得实际的新行覆盖率看起来比实际情况要高。

有没有办法仅检查新行(未更改行)jest --coverage的覆盖率?

示例:整个文件覆盖示例,将超过 95% 的全局阈值。一个新的 if 语句行,没有编写测试:

--------------|---------|----------|---------|---------|-------------------
File          | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
--------------|---------|----------|---------|---------|-------------------
All files     |   96.15 |    95.83 |     100 |   95.83 |                   
changeFile.tsx|   96.15 |    95.83 |     100 |   95.83 | 119               
--------------|---------|----------|---------|---------|-------------------



EXAMPLE: as supposed to NEW line coverage example, will fail if global threshold is 95%, …
Run Code Online (Sandbox Code Playgroud)

javascript typescript reactjs jestjs ts-jest

5
推荐指数
0
解决办法
357
查看次数

使用 typescript 和 esm 运行 jest 时找不到模块“@middy/core”

你好,我正在使用 esm 和 jest 运行 typescript,但 middy 遇到问题:

\n

我做了这个测试:

\n
import { APIGatewayEvent, Context } from \'aws-lambda\';\nimport { lambda } from \'../index.js\';\n\ndescribe(\'get-by-id handler\', () => {\n  test(\'Should not find id\', async () => {\n    const x = jest.fn();\n    x();\n    expect(x).toHaveBeenCalled();\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

它与我在下面提供的配置和npm run test命令配合得很好。\n但是当我将其更改为如下所示时:

\n
import { APIGatewayEvent, Context } from \'aws-lambda\';\nimport { lambda } from \'../index.js\';\n\ndescribe(\'get-by-id handler\', () => {\n  test(\'Should not find id\', async () => {\n    const res = await lambda({\n    pathParameters: { …
Run Code Online (Sandbox Code Playgroud)

node.js typescript jestjs ts-jest middy

5
推荐指数
0
解决办法
562
查看次数

将 Typescript 与 Jest 结合使用时,如何测试超级调用?

假设我有一个结构如下的类:

// Some class that calls super.get() and adds an additional param
export default class ClassB extends ClassA {
   private foo: string;

   constructor(params) {
      super(params);
      this.foo = 'bar';
   }

   public async get(params?: { [key: string]: any }): Promise<any> {
      return super.get({
         foo: this.foo,
         ...params,
      });
   }
}
Run Code Online (Sandbox Code Playgroud)

我想测试是否使用提供的参数以及附加的{ foo: 'bar' }调用 super.get() 。

import ClassA from '../../src/ClassA';
import ClassB from '../../src/ClassB';

jest.mock('../../src/ClassA');
jest.unmock('../../src/ClassB');

describe('ClassB', () => {
   describe('get', () => {
      beforeAll(() => {
        // I've tried mock …
Run Code Online (Sandbox Code Playgroud)

mocking typescript jestjs ts-jest

4
推荐指数
1
解决办法
2313
查看次数

如何使用 jest 和 typescript 测试基本反应功能组件的类型

这有点令人震惊,但我一直试图找到一个简单的例子来说明如何使用 jest 和 typescript 测试一个愚蠢的 react 组件,但我无法成功。我看过:https : //basarat.gitbooks.io/typescript/content/docs/testing/jest.html How to use react-test-renderer/shallow with typescript? 如何在 Jest 单元测试中查看渲染的 React 组件是什么样的?

什么都行不通。大多数时候我得到

Test suite failed to run
'App' refers to a value, but is being used as a type here.
Run Code Online (Sandbox Code Playgroud)

我是新来的反应和开玩笑。我试过反应测试渲染器和酶。在这个阶段我也不介意,最不可知的可能会很棒。

我有什么:这是我的 package.json

{
    "name": "web",
    "version": "1.0.0",
    "description": "mySample",
    "main": "index.js",
    "scripts": {
        "build-dev": "webpack --watch",
        "build": "webpack",
        "start-dev": "nodemon build/server.js",
        "start": "node build/server.js",
        "test": "jest"
    },
    "dependencies": {
        "express": "^4.17.1",
        "react": "^16.8.6",
        "react-dom": "^16.8.6"
    },
    "devDependencies": {
        "@types/enzyme": …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs ts-jest

4
推荐指数
2
解决办法
4412
查看次数

Jest 模拟节点模块不适用于打字稿

我尝试模拟uuid/v4来自 npm的模块。为此,我按照 jest 的建议创建了一个模拟文件夹:https : //jestjs.io/docs/en/manual-mocks

我的文件夹结构:

???__mocks__ 
|  ???uuid
|       ???v4.ts
???src
?   ???__tests__
?   ??? ...
???node_modules
Run Code Online (Sandbox Code Playgroud)

模拟节点模块文件v4.ts

module.exports = jest.fn();
Run Code Online (Sandbox Code Playgroud)

当我尝试在我的测试文件中导入 uuid/v4 时,jest 通常应该导入模拟并且我应该能够使用它。

这是我的测试文件:

import uuidv4 from 'uuid/v4';

it('should create a job', () => {
    const jobId = 'fake-job-id';
    uuidv4.mockReturnValue(jobId); 
    ...
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,模拟导入似乎不起作用,因为我无法添加mockReturnValuejest 提供的内容,并且出现以下打字稿错误: property 'mockReturnValue' does not exist on type v4. ts(2339)

你知道我该如何解决吗?提前致谢。

unit-testing mocking typescript jestjs ts-jest

4
推荐指数
1
解决办法
3464
查看次数

无法使用打字稿设置玩笑

我正在按照此示例为打字稿项目设置一些基本单元测试:https : //dev.to/muhajirdev/unit-testing-with-typescript-and-jest-2gln

我有一个main.ts导出isInternalLink功能

和一个main.spec.ts试图测试它的

但我收到以下错误:

C:\data\devel\apps\tmp\jest-typescript\src\main.spec.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { isInternalLink } from './main.js';
SyntaxError: Unexpected token {
  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
Run Code Online (Sandbox Code Playgroud)

这是带有完整示例的公共存储库:https : //gitlab.com/opensas/jest-typescript

任何人都可以指出我正确的方向,或提供一个有效的例子吗?

typescript jestjs ts-jest

4
推荐指数
2
解决办法
2787
查看次数

如何使用 jest 测试 HttpService.Post 调用

我正在调用 nestjs 服务中的 API,如下所示,

import { HttpService, Post } from '@nestjs/common';

export class MyService {

constructor(private httpClient: HttpService) {}

public myMethod(input: any) {
    return this.httpClient
      .post<any>(
        this.someUrl,
        this.createObject(input.code),
        { headers: this.createHeader() },
      )
      .pipe(map(response => response.data));
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能嘲笑/窥探 this.httpClient.post() 的调用以开玩笑返回响应而不点击实际的 API?

describe('myMethod', () => {
    it('should return the value', async () => {
      const input = {
        code: 'value',
      };
      const result = ['test'];

      // spyOn?

      expect(await myService.myMethod(input)).toBe(result);
  });
});
Run Code Online (Sandbox Code Playgroud)

jestjs nestjs ts-jest

4
推荐指数
2
解决办法
5588
查看次数

当测试/** 未包含在 tsconfig 中时,Vscode TS 语言功能不可用

我希望我的打字稿测试在test文件夹与src. 我不希望在构建打字稿项目时转换测试。

我的打字稿节点项目的结构如下:

.    
??? server
?   ? 
?   ?    
?   ??? src
?   ?   ?
?   ?   ??? app.ts
?   ??? test
?   ?   ?
?   ?   ??? app.test.ts
?   ??? node_modules/
?   ??? package-lock.json
?   ??? package.json
?   ??? tslint.json
?   ??? tsconfig.json
??? front_end/
??? README.md
Run Code Online (Sandbox Code Playgroud)

使用我的 tsconfig:

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "dist",
    "sourceMap": true,
    "strict": true,
    "target": "ESNext",
    "paths": {
      "*": ["node_modules/*"]
    }
  },
  "include": ["src/**/*"] …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs visual-studio-code ts-jest

4
推荐指数
1
解决办法
1298
查看次数

使用笑话和酶模拟自定义 Hook 会导致“xxx 不是函数或其返回值不可迭代”错误

我对笑话和酶很陌生。在我的项目中,我将使用基于 SPA React 的应用程序。包含数据的上下文提供程序,还有几个钩子。我现在使用 Jest(带有 ts-jest 和酶)

\n

我的 jest.config 看起来像这样

\n
module.exports = {\n  "roots": [\n    "<rootDir>/src"\n  ],\n  "transform": {\n    "^.+\\\\.tsx?$": "ts-jest"\n  },\n  "testRegex": "(/__tests__/.*|(\\\\.|/)(test|spec))\\\\.tsx?$",\n  "moduleFileExtensions": [\n    "ts",\n    "tsx",\n    "js",\n    "jsx",\n    "json",\n    "node"\n  ],\n  "snapshotSerializers": ["enzyme-to-json/serializer"]\n
Run Code Online (Sandbox Code Playgroud)\n

所以我的第一步是测试 UI 组件是否有效。\n下一步是使用模拟数据测试组件。但我得到了底部描述的错误。

\n

我有一个像这样的功能组件:

\n
export default function CurrentWeather(props: ICurrentWeatherProps) {\n    const [data, Reload] = useCurrentWeather(props.locationID);\n    return (<div>......</div>)\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

您会注意到这个useCurrentWeather钩子,这是其代码:

\n
import { useEffect, useState } from 'react';\nimport { useLocationState } from '../context/locationContext';\nimport { ILocationData } from './useLocations';\nimport _ …
Run Code Online (Sandbox Code Playgroud)

jestjs enzyme react-scripts ts-jest react-typescript

4
推荐指数
1
解决办法
3875
查看次数