标签: ts-jest

为什么 Jest 测试有时会在 CircleCI 上失败?

我有针对 dockerized Neo4j 数据库运行的 Jest 测试,有时它们在 CircleCI 上失败。所有 25 个以上的错误消息是:

thrown: "Exceeded timeout of 5000 ms for a hook.
@*******api:     Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
Run Code Online (Sandbox Code Playgroud)

由于它们有时会失败,例如每 25 次运行一次,我想知道是否jest.setTimeout可以解决该问题。我能够通过设置在本地使它们失败jest.setTimeout(10),但我不确定如何进一步调试它,或者除了小超时(默认 5000)之外是否还有其他问题。如果 1/25 或少数失败,或者所有其他套装都失败,我会理解,但只有一个包含该文件中所有测试的文件失败。而且它始终是同一个文件,因此永远不会是其他文件。

附加信息,在本地,单个文件在连接到临时数据库的时间内运行不到 1000 毫秒,与运行时只有几个文件的 dockerized 相比,这是巨大的

unit-testing docker circleci jestjs ts-jest

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

在使用 jest/ts-jest 模拟打字稿中的类时,我收到“TypeError: "X".default is not a constructor。”

我正在使用打字稿中的 jest/ts-jest 编写单元测试,我正在尝试模拟一个类,但我收到了 TypeError。“storage_1.default 不是构造函数”。

这是我嘲笑班级的方式。

index.test.ts

import GetAdaptiveCard from '../../GetAdaptiveCard/index'

const mockGetAdaptiveCard = jest.fn();
jest.mock('../../utils/storage', () => {
    return jest.fn().mockImplementation(() => {
        return {
            getAdaptiveCard: mockGetAdaptiveCard
        }   
    })
})
test('http trigger should return adaptive card', async () => {
....
    await GetAdaptiveCard(context, req);//calls AdaptiveCardStorage. The class I am mocking in "../../utils/storage"
...
});

Run Code Online (Sandbox Code Playgroud)

索引.ts

import AdaptiveCardsStorage from '../utils/storage';
...
const storage: AdaptiveCardsStorage = new AdaptiveCardsStorage(); //This is where I get the TypeError
const adaptiveCard: string = await storage.getAdaptiveCard(userID, cardName); …
Run Code Online (Sandbox Code Playgroud)

mocking typescript jestjs ts-jest

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

打字稿 - 我无法用 jest、@types/jest 和 ts-jest 编译项目

我正在尝试使用 jest 来模拟我的axios请求。这是我的测试:

// External imports
import axios, { AxiosPromise } from 'axios'

// Personal imports
import { getProgramApplications } from '#stores'
import { programItem } from '../fixtures/zanox'

describe('Zanox sales', async function () {
    describe('Get program applications', async function () {
        it('should get program applications', async function () {
            const program = programItem()
            const mock = jest.spyOn(axios, 'get')
            mock.mockReturnValueOnce({ data: [program] } as unknown as AxiosPromise<unknown>)
            getProgramApplications(process.env.ZANOX_ADSPACE!)
        })
    })
})
Run Code Online (Sandbox Code Playgroud)

这是我的package.json

{
    "name": "zanox",
    "version": "1.0.0", …
Run Code Online (Sandbox Code Playgroud)

javascript typescript tsconfig jestjs ts-jest

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

Jest TypeScript 测试在 Jenkins 中失败

我们有一个 React / TypeScript 项目,并使用 Jest + ts-jest 作为我们的测试运行器。在本地一切正常,但在我们的 Jenkins CI 中运行时失败。

以下是 Jenkins 控制台的片段:

No tests found, exiting with code 1
In /var/lib/jenkins/workspace/fix-jenkins-tests
  403 files checked.
  testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[jt]s?(x) - 38 matches
  testPathIgnorePatterns: /lib/, /node_modules/ - 0 matches
  testRegex:  - 0 matches
Pattern:  - 0 matches
error Command failed with exit code 1.
Run Code Online (Sandbox Code Playgroud)

奇怪的是,Jest 说“没有找到测试”,但也说“testMatch:... 38 个匹配”

jenkins typescript jestjs jenkins-pipeline ts-jest

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

开玩笑地嘲笑谷歌云/存储打字稿

我一直在尝试为我的实现模拟 @google-cloud/storage 以便我可以测试它而不必在 gcp 中点击 cloud-storge 到目前为止它都是徒劳的我试图模拟 node_module 范围文件夹使用 jest doc 并没有解决因此我尝试在下面使用

这是我的实现类

import { GcloudAuthenticationInstance } from '../common/services/gcloud.authentication';
import * as fs from 'fs';
import pump from 'pump';
import pino from 'pino';
import * as _ from 'lodash';

import {
    ENV_NAME_DEV,
    GCLOUD_DATABASE_BUCKET_DEV,
    GCLOUD_DATABASE_BUCKET_PROD,
    GCLOUD_ENV_STR_BUCKET_NAME,
    GCLOUD_STORED_FILE_NAME_DEV,
    GCLOUD_STORED_FILE_NAME_PROD,
    GCLOUD_UPLOAD_FILE_DEV_LOCAL_PATH,
    GCLOUD_UPLOAD_FILE_PROD_LOCAL_PATH,
} from '../common/util/app.constants';
import { PinoLoggerServiceInstance } from '../common/services/pino.logger.service';
import { AppUtilServiceInstance } from '../common/services/app.util.service';
export const uploadEnvFiles = async (env_name: string) => {
    const LOGGER: pino.Logger = PinoLoggerServiceInstance.getLogger(__filename);

    return new …
Run Code Online (Sandbox Code Playgroud)

node.js google-cloud-storage typescript google-api-nodejs-client ts-jest

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

Typescript Jest 模拟:xx.default 不是构造函数:无法实例化模拟

我在尝试模拟类和构造函数时遇到问题。

我有一个要测试的 App.ts 类:

class App {
  public server: Express;

  constructor() {
    this.server = new Express();
    this.server.init();
  }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

对于测试场景 -> 一旦我实例化一个 App 类,它应该: - 确保创建了类 Express 的新实例 - 确保调用了 init 函数

所以我有我的 App.test 文件:

import App from '../App';

let mockedExp: jest.Mock;
jest.mock('../Express', () => {
  return {
    default: jest.fn().mockImplementation(() => {
      return {
        init: mockedExp,
      };
    }),
  };
});

describe('App', () => {
  beforeEach(() => {
    mockedExp = jest.fn().mockImplementation();
    mockedExp.mockClear();
  });

  it('Should call init from express …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs ts-jest

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

如何在 jest 中测试 if 条件和 return 语句?

我刚刚开始学习 Jest。使用 Jest 测试此函数的 If case 和 return 语句还有哪些其他方法?这是用 Jest 测试的函数

const extractInfo = (description: string) => {
        const info= description.match('descriptionInformation');
        if (info) {
          return info[0];
          }
         return 'hello jest';
        };
Run Code Online (Sandbox Code Playgroud)

尝试下面的测试用例来检查 Info.test.ts

  test('extractInfo method to be defined', () => {
    expect(extractInfo ).toBeDefined();
  });

  test('extractInfo to be called when Info has blank string', () => {
    const BLANK_STRING = '';
    expect(extractInfo ).toHaveBeenCalled();
    expect(extractInfo ).toHaveBeenCalledWith(BLANK_STRING);
  })

    const extractInfo = (Info: string) => {
        const info= description.match(jestinformation);
        if (info) {
          return info[0]; …
Run Code Online (Sandbox Code Playgroud)

javascript typescript jestjs ts-jest

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

解析 jest.mock 中的 TypeScript 路径

我正在向使用 的 TypeScript 项目添加单元测试compilerOptions.paths,并且我需要模拟导入。

\n

我遇到了一个问题,jest 无法解析要模拟的模块

\n
 FAIL  logic/index.test.ts\n  \xe2\x97\x8f Test suite failed to run\n\n    Cannot find module \'@lib/foo\' from \'logic/index.test.ts\'\n
Run Code Online (Sandbox Code Playgroud)\n

我正在使用ts-jest它添加对导入中路径的支持,但看起来我需要为模拟执行额外的步骤

\n

解决这里路径的正确方法是什么?

\n
\n

简化案例

\n
{\n  "baseUrl": ".",\n  "compilerOptions": {\n    "paths": {\n      "@lib/*": ["lib/*"]\n    }\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

文件系统

\n
* lib\n  * __mocks__\n    * foo.ts\n  * foo.ts\n* logic\n  * index.ts\n  * index.test.ts\n* tsconfig.json\n* jest.config.js\n
Run Code Online (Sandbox Code Playgroud)\n
// index.ts\nimport foo from \'@lib/foo\';\n\nconst logic = () => foo();\n\nexport default logic;\n
Run Code Online (Sandbox Code Playgroud)\n
// index.test.ts\nimport \'jest\';\n\nimport …
Run Code Online (Sandbox Code Playgroud)

unit-testing typescript jestjs ts-jest

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

如何使用 jest 和 TypeScript 测试 Express 中间件错误处理程序

我对用笑话测试中间件完全陌生

中间件

import HttpException from "../common/http-exception";
import { Request, Response, NextFunction } from "express";

export const errorHandler = (
  error: HttpException,
  request: Request,
  response: Response,
  next: NextFunction
) => {
  const status = error.statusCode || error.status || 500;

  response.status(status).send(error);
};

Run Code Online (Sandbox Code Playgroud)

损坏的测试给出错误 TypeError: Cannot read property 'send' of undefined

import HttpException from "../src/common/http-exception";
import { NextFunction, Request, Response, response } from "express";
import { errorHandler } from "../src/middleware/error.middleware";

describe("Error handler middleware", () => {
  const error: HttpException = {
    name: "error", …
Run Code Online (Sandbox Code Playgroud)

typescript ts-jest

0
推荐指数
1
解决办法
2625
查看次数

循环遍历数组并对每个元素运行 Jest 测试不起作用

我有一个非常大的 JSON 对象数组。我需要对每个单独的元素运行 Jest 测试。我尝试首先迭代数组,然后在循环中编写测试,如下所示:

describe("Tests", (f) => {
  it("has all fields and they are valid", () => {
    expect(f.portions! >= 0).toBeTruthy();
    expect(f.name.length > 0 && typeof f.name === "string").toBeTruthy();
  });

  it("has an image", () => {
    expect(f.image).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

然而,对于这段代码,Jest 抱怨“你的测试套件必须至少包含一个测试”。

我是否必须为每个测试循环遍历这个数组?

javascript testing node.js jestjs ts-jest

0
推荐指数
1
解决办法
7093
查看次数

NodeJS 单元测试 RabbitMQ / Amqplib

我正在尝试为我的项目开发测试,我有一个连接到rabbitmq并消耗队列的文件,但我在测试它时遇到了问题

const amqp = require('amqplib/callback_api');

const rabbitConsumer = (io) => {
  setTimeout(() => {
    amqp.connect('amqp://rabbitmq', (error0, connection) => {
      if (error0) {
        throw error0;
      }
      connection.createChannel((error1, channel) => {
        if (error1) {
          throw error1;
        }
        const queue = 'message';

        channel.assertQueue(queue, {
          durable: false,
        });

        console.log(' [*] Waiting for message', queue);

        channel.consume(
          queue,
          (data) => {
            console.log(' [x] Received data:', data.content.toString('utf-8'));
            io.emit('sendMessage', data.content.toString('utf-8'));
          },
          {
            noAck: true,
          }
        );
      });
    });
  }, 10000);
};

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

可以测试这个文件吗?我如何使用 JEST 或任何其他库来做到这一点?

tdd unit-testing rabbitmq node.js ts-jest

0
推荐指数
1
解决办法
4610
查看次数

无法在 Jest 中模拟 jwt-decode

出于测试目的,我需要模拟 jwt-decode 函数,但我在这里找到的建议都没有帮助。使用 jwtDecode 的代码如下所示

 import jwtDecode from 'jwt-decode';
 ...
 const { exp } = jwtDecode(accessToken);
Run Code Online (Sandbox Code Playgroud)

在测试中我需要模拟这个返回exp值。我尝试按照Mock jwt-decode in Jest中的建议来模拟它

jest.mock('jwt-decode', () => () => ({ exp: 123456 }));
const { exp } = jwtDecode('123456');
Run Code Online (Sandbox Code Playgroud)

但这会返回

InvalidTokenError:指定的令牌无效:无法读取未定义的属性“替换”

testing mocking typescript ts-jest

0
推荐指数
1
解决办法
3867
查看次数