标签: ts-jest

我无法正确配置 jest 来导入模块 (setupFilesAfterEnv)

我使用它是@angular-builders/jest为了在测试角度项目时用玩笑替换业力。我喜欢有 2 个库为 jest:jest-extended和获取额外的匹配器@testing-library/jest-dom

我找不到自动导入匹配器的方法,这样我就不必在每个规范文件中导入它们。

重现问题的最小示例jest-extended

首先,创建一个 Angular 项目并安装 jest 依赖项

ng new --defaults my-project
cd my-project
yarn add -D jest @types/jest @angular-builders/jest jest-extended
Run Code Online (Sandbox Code Playgroud)

然后编辑angular.json以替换构建器

...
"test": {
    "builder": "@angular-builders/jest:run"
},
Run Code Online (Sandbox Code Playgroud)

到目前为止,我可以使用 jest 和命令运行并通过测试

...
"test": {
    "builder": "@angular-builders/jest:run"
},
Run Code Online (Sandbox Code Playgroud)

现在,我使用一个笑话扩展匹配器添加一个测试。在app.component.spec.ts

...
  it('should work with jest-extended matchers', () => {
    expect([1, 1, 1]).toBeArrayOfSize(3);
  });
Run Code Online (Sandbox Code Playgroud)

尝试#1

创造jest.config.js

ng test
Run Code Online (Sandbox Code Playgroud)

不起作用,我收到错误TS2339: Property 'toBeArrayOfSize' does not exist on type 'ArrayLikeMatchers<number>' …

testing typescript jestjs angular ts-jest

2
推荐指数
1
解决办法
8374
查看次数

按照 Jest Docs,在 mockImplementation() 上出现错误。我究竟做错了什么?

我正在尽力遵循笑话文档,并且我也在尽力自学。我在关注官方笑话网站上的文档时遇到问题。我在模拟模块部分。它与 axios 有关,但我不断在打字稿中收到错误,该错误表明该模拟实现不是其属性(无论模拟是什么)

我尝试环顾四周,看看这是否是我的配置的问题,但我无法弄清楚。

脚.ts

// foo.ts
export default function() {
    // some implementation;
  };
Run Code Online (Sandbox Code Playgroud)

测试.ts

import foo from '../src/foo';

// test.js
jest.mock('../src/foo'); // this happens automatically with automocking
foo.mockImplementation(() => 42);
foo();
console.log(foo())
Run Code Online (Sandbox Code Playgroud)

这是我在mockImplementatin上遇到的错误

Property 'mockImplementation' does not exist on type '() => void'.ts(2339)
Run Code Online (Sandbox Code Playgroud)

我所做的就是遵循文档。在我进行分区之前我没有遇到任何问题。

typescript jestjs ts-jest

2
推荐指数
1
解决办法
2412
查看次数

由于模块js文件中的“导入”,ts-jest无法运行tsx测试文件

我试图用来ts-jest运行tsx测试文件form.spec.tsx

form.spec.tsx进口React Quill编辑器和一些插件。

我如何绕过SyntaxError: Unexpected identifier来自导入的名为quill-mention的插件的错误Quill?该模块涉及form.spec.tsx

我已经["<rootDir>/node_modules/"]在笑话配置中添加到transformIgnorePatterns字段,但是/node_modules/quill-mention/src/quill.mention.js中仍然存在此问题

  ? Test suite failed to run

    /home/web/node_modules/quill-mention/src/quill.mention.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Quill from 'quill';
                                                                                                    ^^^^^

    SyntaxError: Unexpected identifier

      1 | import React from "react"
    > 2 | import "quill-mention";
        | ^
Run Code Online (Sandbox Code Playgroud)

form.spec.tsx:

import {render, RenderResult, waitForElement} from "react-testing-library";
import ReactQuill, {Quill} from 'react-quill';
import "quill-mention";

const renderResult = render(
        <ReactQuill
            modules={
             {
                mention: {
                   allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/, …
Run Code Online (Sandbox Code Playgroud)

javascript typescript reactjs jestjs ts-jest

2
推荐指数
1
解决办法
263
查看次数

Angular 测试 - 将 Jest 与 Protractor 一起使用

我是 Angular 测试的新手,我想为我的应用程序执行两种测试:

  1. 单元测试 - 我选择使用Jest,因为我可以在不打开浏览器的情况下运行我的测试,并且它还支持使用--testNamePatern测试特定情况。
  2. 端到端测试 - 我想试用Protractor,因为它在 Angular 中可用,并且还有一个很大的 Angular 社区可以使用。

我的问题是,我可以在我的应用程序中同时使用 Jest 和 Protractor 吗?如果是,我是否需要配置任何东西才能在我的应用程序中使用它们。

protractor ts-jest angular8

2
推荐指数
1
解决办法
2955
查看次数

如何使用不同的 jest.config.js 进行单元和组件测试?

我正在尝试为应用程序的组件级测试创建一套单独的测试。

在这个单独的套件中,我需要一个自定义测试环境来引导一些持久层模拟,并且这些测试将与我的单元测试放在我的项目结构中的一个单独文件夹中。

例如,单元测试将在__tests__文件夹中的代码附近,而组件测试将在顶级tests/目录中。

我已经有我的大部分jest.config.js设置的,但是当我加入了projects部分重写某些字段,特别是testMatchtestEnvironment它完全不理会在全球指定我的配置。

现在我一直在读到projects配置主要是关于 monorepo 设置,所以我认为这不是正确的方法。

理想情况下,我可以jest.config.js在我的tests/目录中有一个单独的目录,但我不知道如何设置它,如果它甚至有效。

对此问题的任何见解都会有所帮助。提前致谢。

javascript testing jestjs ts-jest

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

如何重写got.post()处的返回方法(使用jest模拟),以便我可以调用json方法

我尝试使用 jest 来测试我的脚本(打字稿)

// api.ts
import got from "got";


export const run = async () => {
  const body = await got.get('https://jsonplaceholder.typicode.com/posts/1').json();
  return body;
};
Run Code Online (Sandbox Code Playgroud)

和我的测试

// api.test.ts
import { run } from "../api";
import got from "got";
import { mocked } from "ts-jest/dist/util/testing";

jest.mock("got");

test("using another got", async () => {
  const response = {
    get: jest.fn(),
  };
  mocked(got).mockResolvedValue(response);

  const result = await anotherGot();
  console.log(result);
  // expect(result).toBe(response.body);
});
Run Code Online (Sandbox Code Playgroud)

当我尝试运行测试 ( npm test) 时出现错误

TypeError: Cannot read property 'json' …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs ts-jest

2
推荐指数
1
解决办法
4873
查看次数

与打字稿开玩笑不允许直接导入默认导出

我有一个使用 Typescript 编写的 React 应用程序。下面是我在项目中使用的 tsconfig。我能够正确导入默认值,没有任何问题。我所有的文件都有import React from 'react'.

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "esnext",
    "moduleResolution": "node",
    "outDir": "./dist/",
    "target": "es2016",
    "jsx": "react",
    "allowJs": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noUnusedLocals": true,
    "types": ["jest"],
    "allowSyntheticDefaultImports": true,
    "paths": {
      "protractor": ["integration-tests/protractor.d.ts"]
    },
  },
  "exclude": [".yarn", "**/node_modules", "dist"],
  "include": ["**/*.js", "**/*.jsx", "**/*.ts", "**/*.tsx", "**/*.json"]
}

Run Code Online (Sandbox Code Playgroud)

但是当我使用 Jest 运行单元测试时,jest 抱怨默认值。因此,Jest 不喜欢默认值并抱怨它是未定义的。我正在使用 ts-jest 进行转换。我开玩笑时是否缺少一个配置来检测正常 es6 方式的默认值?

需要明确的是,我可以像这样导入,import * as React from 'react'但我想使用标准 ES6 导入方式,而import React from 'react'不是打字稿方式。

typescript jestjs ts-jest

2
推荐指数
1
解决办法
3486
查看次数

如何让 Jest 覆盖仅限出口线路?

index.ts在 NPM 库中有一个顶级文件,其中仅包含导出语句。

IE:

export * from "./foo"
export * from "./bar"
Run Code Online (Sandbox Code Playgroud)

SonarCloud 将这些线路显示为未覆盖,因为预计这些线路不应进行测试。我知道我们可以忍受缺少报道,但这在某种程度上很烦人。

我知道我也可以忽略该文件,但随后我需要对具有类似目的的每个文件执行相同的操作,将组件分组并导出到库内。

我可以使用任何最佳实践或配置来克服这个问题吗?

typescript sonarqube jestjs sonarcloud ts-jest

2
推荐指数
1
解决办法
2250
查看次数

TypeError: Jest: 一个转换必须导出一个 `process` 函数

最近将我的应用程序升级到 Angular 11。Jest 已被设置为默认测试框架。运行 npm test 会导致以下错误:

? Test suite failed to run

    TypeError: Jest: a transform must export a `process` function.

      20 | @Component({
      21 |     selector: 'app-bx-input-textbox',
    > 22 |     template: require('./bx-input-textbox.component.html'),
         |               ^
      23 |     styles: [String(require('./bx-input-textbox.component.scss'))],
      24 |     providers: [
      25 |         {

      at ScriptTransformer._getTransformer (node_modules/@jest/transform/build/ScriptTransformer.js:357:15)
      at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:419:28)
      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:523:40)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
      at src/app/core/components/bx-input-textbox/bx-input-textbox.component.ts:22:15
      at Object.<anonymous> (src/app/core/components/bx-input-textbox/bx-input-textbox.component.ts:38:1)
Run Code Online (Sandbox Code Playgroud)

// jest.config.js

module.exports = {
  testEnvironment: "jsdom",
  transform: {
    ".+\\.(css|styl|less|sass|scss)$": "<rootDir>/node_modules/jest-css-modules-transform",
    "\\.(ts|js)$": ['ts-jest']
  },
  setupFilesAfterEnv: ['./jest.setup.js'], …
Run Code Online (Sandbox Code Playgroud)

jestjs angular ts-jest

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

用 jest 测试对象结构

我需要一些建议,目前我想测试对象集合中的每个对象是否都具有正确的结构,所以我这样做:

const allExercises = listAllExercises()

describe("listAllExercises | should return all exercises", () => {
  test("Each exercise should have the right structure", () => {
    const keys = [
      "name",
      "execution",
      "level",
      "is_poly_articular",
      "practice",
      "gender",
      "body_focus",
    ]

    allExercises.forEach((exercise) => {
      expect(Object.keys(exercise).sort()).toEqual(keys.sort())
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但我想知道这是否是正确的方法,你有更好的解决方案来用笑话测试对象的键吗?

javascript typescript jestjs ts-jest

2
推荐指数
1
解决办法
1669
查看次数