我在后端使用带有 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) 测试 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)
该进程进入解析方法并抛出错误“您尝试访问的存储桶必须使用特定端点进行寻址”
我正在尝试使用 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) 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 。我现在该怎么办?
问题描述:
我为一个打字稿类编写了两个测试。这两个测试都通过了,所以 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) 我有一个使用 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) 我们在 CI 中使用 Bitbucket 管道进行测试,我们的应用程序是 NestJS,并使用 Jest 测试了 Typescript。
我们总是让所有测试都运行,但是从现在开始的几天(2022 年 5 月)测试在一些套装后会卡住,测试卡住的套件是相当随机的。
测试不会失败,我们没有任何内存警告或其他任何东西,它只是卡在管道上。我们需要停止管道,因为它永远不会停止。
不幸的是,我们没有发现任何错误,需要进一步调查。
我们可以做什么来检查更多细节?
我想强烈地打我的笑话。在某种程度上,我可以使它工作,但是当一个类具有私有属性时,我就被卡住了。
另一个问题是,当我使用模拟(当前使用的方式)时,返回类型是原始类型,但是当我必须访问Jest添加的任何方法时,我必须进行类型转换jest.Mock以访问方法。有一个更好的方法吗?我试图与工作jest.Mock,jest.Mocked,jest.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) 根据文档,可以使用jest-object将默认异步超时从 5000 毫秒增加
更具体地说,通过使用jestsettimeouttimeout
我面临的问题是我正在针对一个非常慢的 API 运行一系列测试,响应时间为 5-15 秒,在每个测试的顶部配置这个 jest 对象非常烦人。
是否可以在运行所有测试文件之前声明一次这些设置?
我正在使用 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) ts-jest ×10
jestjs ×8
typescript ×5
node.js ×3
amazon-s3 ×1
aws-sdk-js ×1
babel-jest ×1
bitbucket ×1
nestjs ×1
reactjs ×1
testing ×1
vue.js ×1
vuetify.js ×1