标签: ts-jest

Jest 测试通过但得到错误:最后连接 ECONNREFUSED 127.0.0.1:80

我在后端使用带有 TypeScript 的节点,在后端使用 Jest 和 Supertest 作为我的测试框架。

当我尝试测试时,结果通过了,但最后出现错误。结果如下:

 PASS  test/controllers/user.controller.test.ts
  Get all users
    ? should return status code 200 (25ms)

  console.log node_modules/@overnightjs/logger/lib/Logger.js:173
    [2019-12-05T04:54:26.811Z]: Setting up database ...

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.284s
Ran all test suites.
server/test/controllers/user.controller.test.ts:32
                throw err;
                ^

Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1104:14)
npm ERR! Test failed.  See above for more details.
Run Code Online (Sandbox Code Playgroud)

这是我的测试代码:

import request from "supertest";
import { AppServer } from '../../config/server'; …
Run Code Online (Sandbox Code Playgroud)

testing node.js jestjs ts-jest

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

如何使用 v3 sdk 通过 jest 模拟 AWS S3 GetObjectCommand?

测试 s3 上传?测试的方法是

export class ProcessData {
  constructor() {}

  async process(): Promise<void> {
     const data = await s3Client.send(new GetObjectCommand(bucket));
     await parseCsvData(data.Body)
}
Run Code Online (Sandbox Code Playgroud)

这是我对测试用例的尝试。

import {S3Client} from '@aws-sdk/client-s3';
jest.mock("aws-sdk/clients/s3", () => {
  return {
    S3Client: jest.fn(() => {
        send: jest.fn().mockImplementation(() => {
            data:  Buffer.from(require("fs").readFileSync(path.resolve(__dirname, "test.csv")));
        })
    })
  }
});

describe("@aws-sdk/client-s3 mock", () => {
  test('CSV Happy path', async () => {
    const processData = new ProcessData()
    await processData.process()
  }
}
Run Code Online (Sandbox Code Playgroud)

该进程进入解析方法并抛出错误“您尝试访问的存储桶必须使用特定端点进行寻址”

amazon-s3 amazon-web-services typescript aws-sdk-js ts-jest

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

NodeJS - 使用 Jest 运行测试:TypeScript 配置文件出现错误

我正在尝试使用 Jest 运行一些测试,但我不断收到错误。这与 TypeScript 配置文件有关,我已经搜索过但没有找到太多。我正在使用 NodeJS、TypeORM 和 TypeScript。

我在运行时收到此错误 yarn test

错误:Jest:无法解析 TypeScript 配置文件

C:\Users\demis\Documents\Projects\Personal\nlw_node\jest.config.ts TypeError: registerer.enabled 不是 readConfigFileAndSetRootDir 处的函数*** (C:\Users\demis\Documents\Projects\Personal\nlw_node\ node_modules\jest-config\build\readConfigFileAndSetRootDir.js:150:13) 在 readConfig (C:\Users\demis\Documents\Projects\Personal\nlw_node\node_modules\jest-config\build\index.js:217:18)在 readConfigs (C:\Users\demis\Documents\Projects\Personal\nlw_node\node_modules\jest-config\build\index.js:406:26) 在 runCLI (C:\Users\demis\Documents\Projects\Personal\ nlw_node\node_modules@jest\core\build\cli\index.js:230:59) 在 Object.run (C:\Users\demis\Documents\Projects\Personal\nlw_node\node_modules\jest-cli\build\cli\索引.js:163:37)

First.test.ts:

describe("First", () => {
  it("should", () => {
    expect(2 + 2).toBe(4);
  });
});
Run Code Online (Sandbox Code Playgroud)

jest.config.ts:

export default {
  bail: true,
  clearMocks: true,
  coverageProvider: "v8",
  preset: "ts-jest",
  testEnvironment: "node",
  testMatch: ["**/tests/*.test.ts"]
};
Run Code Online (Sandbox Code Playgroud)

tsconfig.json:

{
   "compilerOptions": {
      "lib": [
         "es5",
         "es6"
      ],
      "target": "es5", …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs ts-jest

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

无法从“jest.setup.js”中找到模块“@testing-library/jest-dom/extend-expect”

import '@testing-library/jest-dom/extend-expect';


expect(screen.getByText('User does not exist.')).toBeInTheDocument()
Run Code Online (Sandbox Code Playgroud)

我正在为我的网络应用程序编写单元测试,我在代码中使用 toBeInTheDocument() ,但是在终端中运行 npm test 后,它显示“找不到模块”@testing-library/jest-dom/extend-expect '来自'jest.setup.js''。

我有一个 jest.setup.js 文件,其中包含代码:require('@testing-library/jest-dom/extend-expect');

还有一个 jest.config.js 文件,其中包含代码: setupFilesAfterEnv:["./jest.setup.js"],

我还导入 '@testing-library/jest-dom/extend-expect'; 在我的 test.tsx 文件中,还要检查 node_modules 下是否有 @testing-library/jest-dom 。我现在该怎么办?

reactjs ts-jest

13
推荐指数
3
解决办法
8793
查看次数

Jest 通过测试但 --covering 选项不拾取文件

问题描述:
我为一个打字稿类编写了两个测试。这两个测试都通过了,所以 jest 成功地检索了测试文件。然后我使用 --coverage 选项,但似乎开玩笑没有在这里选择涵盖的文件。
这是我得到的输出:

api_jester    | PASS src/tests/repositories/user.test.ts
api_jester    |   User Repository
api_jester    |     ? it should return an empty array (18ms)
api_jester    |     ? should successfully create a user and return its data (7ms)
api_jester    | 
api_jester    | ----------|----------|----------|----------|----------|-------------------|
api_jester    | File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
api_jester    | ----------|----------|----------|----------|----------|-------------------|
api_jester    | All files |        0 |        0 |        0 |        0 |                   | …
Run Code Online (Sandbox Code Playgroud)

node.js typescript jestjs babel-jest ts-jest

12
推荐指数
1
解决办法
8042
查看次数

jest.mock 找不到模块

我有一个使用 mysql 连接进行查询的函数,我正在尝试对该函数进行单元测试,为此我需要模拟 mysql。但是,当我使用 jest.mock 函数来模拟 mysql 连接时,它返回以下错误。

无法从“src/api/leaderboard/ranks/popularity.test.ts”找到模块“MySQLReplica”

流行度.test.ts

import { MySQLReplica } from "@services/mysql.service";
import { IEntityLeaderboardQuery } from "./../leaderboard.interface";
import { PopularityRank } from "./popularity";
import { mocked } from "ts-jest/utils";
jest.mock("MySQLReplica");

describe("Leaderboard - Rank - Popularity", () => {
    afterAll(() => {
        MySQLReplica.end();
    });

    const mockedMySQLReplica = mocked(MySQLReplica, true);
    it("should get popularity scores", async () => {
        const query: IEntityLeaderboardQuery = {
            top: "10",
            entity_types: ["person"],
            region: "Europe",
            country: "Germany",
            end_date: "2021-06-15",
            start_date: "2021-06-01",
            rank: "popularity", …
Run Code Online (Sandbox Code Playgroud)

node.js jestjs ts-jest

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

Jest 测试卡在 bitbucket 管道上,没有任何错误

我们在 CI 中使用 Bitbucket 管道进行测试,我们的应用程序是 NestJS,并使用 Jest 测试了 Typescript。

我们总是让所有测试都运行,但是从现在开始的几天(2022 年 5 月)测试在一些套装后会卡住,测试卡住的套件是相当随机的。

测试不会失败,我们没有任何内存警告或其他任何东西,它只是卡在管道上。我们需要停止管道,因为它永远不会停止。

不幸的是,我们没有发现任何错误,需要进一步调查。

我们可以做什么来检查更多细节?

bitbucket jestjs bitbucket-pipelines nestjs ts-jest

12
推荐指数
1
解决办法
4233
查看次数

如何强力输入笑话模拟

我想强烈地打我的笑话。在某种程度上,我可以使它工作,但是当一个类具有私有属性时,我就被卡住了。

另一个问题是,当我使用模拟(当前使用的方式)时,返回类型是原始类型,但是当我必须访问Jest添加的任何方法时,我必须进行类型转换jest.Mock以访问方法。有一个更好的方法吗?我试图与工作jest.Mockjest.Mockedjest.MockInstance

如果有人能指出我正确的方向,那就太好了!

class MyTest {
    constructor(private readonly msg: string) {}

    public foo(): string {
        return this.msg;
    }
}

const myTestMock: jest.Mock<MyTest, [string]> = jest.fn<MyTest, [string]>(() => ({
    msg: 'private',
    foo: jest.fn().mockReturnValue('aaa'),
}));
// Results in error:
// Type '{ msg: string; foo: Mock<any, any>; }' is not assignable to type 'MyTest'.
// Property 'msg' is private in type 'MyTest' but not in type '{ msg: string; foo: Mock<any, any>; }'

const …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs typescript-typings ts-jest

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

为所有测试配置一次开玩笑超时

根据文档,可以使用jest-object将默认异步超时从 5000 毫秒增加

更具体地说,通过使用jestsettimeouttimeout

我面临的问题是我正在针对一个非常慢的 API 运行一系列测试,响应时间为 5-15 秒,在每个测试的顶部配置这个 jest 对象非常烦人。

是否可以在运行所有测试文件之前声明一次这些设置?

jestjs ts-jest

11
推荐指数
4
解决办法
9361
查看次数

Vuetify Jest 未知自定义元素 &lt;v-*&gt;

我正在使用 Jest 为我的项目编写单元测试。项目基于 Vue、Vuetify (1.5) 和 TypeScript(以及 vue-property-decorator)。

我有基本的包装器<v-btn>。它看起来像这样:

<template>
  <v-btn
    :round="!square"
    v-on="$listeners"
  >
    <slot />
  </v-btn>
</template>

<script lang="ts">
import { Vue, Prop, Component } from 'vue-property-decorator';

import { VBtn } from 'vuetify/lib';

@Component({
  components: {
    VBtn,
  },
})
export default class Btn extends Vue {
  @Prop({ default: false, type: Boolean }) private square!: boolean;
}
</script>
Run Code Online (Sandbox Code Playgroud)

我写了基本测试,只是为了挂载这个组件:

import { mount } from '@vue/test-utils'
import Vue from 'vue';
import Btn from './Btn.vue';

describe('Btn', () => {

  it('should …
Run Code Online (Sandbox Code Playgroud)

typescript vue.js jestjs vuetify.js ts-jest

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