标签: ts-jest

使用 Jest 的 todo 功能

Jest 24发行说明强调了一个我想使用的新功能:test.todo. 但是,对于我的一生,我无法使用它。

例如,我想在我的subscriptions.test.ts文件中勾画测试,所以我创建了以下内容:

describe('Subscription Tests', () => {
    test.todo('... a name');
});
Run Code Online (Sandbox Code Playgroud)

然后,TypeScript 编译器会立即向我显示一条红线,下面todo说:Property 'todo' does not exist on type 'It'.

我确定我遗漏了一些明显的东西,但此时我已经撞墙了。有人可以帮忙吗?

javascript typescript jestjs ts-jest

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

与 TS 和 ES2022 进行玩笑 & NodeNext 失败

这是下面的演示代码,用于演示我在当前项目中遇到的失败。

它编译并运行,只是无法使用笑话进行编译,并出现以下错误

错误:错误 TS1343:仅当“--module”选项为“es2020”、“es2022”、“esnext”、“system”、“node16”或“nodenext”时,才允许使用“import.meta”元属性。

文件:src/calc.ts

import { fileURLToPath } from 'url';
import path from 'path';
const __dirname = path.dirname(fileURLToPath(import.meta.url));

export function add(x: number, y: number): number {
  return x + y;
}

export function mul(x: number, y: number): number {
  return x * y;
}
Run Code Online (Sandbox Code Playgroud)

jest.config.cjs:

 module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};
Run Code Online (Sandbox Code Playgroud)

tsconfig.json:

    {
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "node_modules"
  ],
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "outDir": "./out",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs ts-jest

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

错误:不变的预期应用程序路由器要安装为什么在使用反应测试库时发生这种情况

当我使用react-testing-library时,它说错误:不变的预期应用程序路由器要安装,在开发环境中运行时没有这样的问题。

测试逻辑在这里

import { render, screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import NavBar from "@/components/NavBar";

describe("<NavBar>", () => {
    it ("the login pop out displayed after click the login/sign up button", async () => {
        render(<NavBar />);

        const loginButton = screen.getByRole("link", {
            name: "LOGIN/SIGN UP"
        });
        const loginCard = screen.getByTestId("loginCard");

        await userEvent.click(loginButton);
        expect(loginButton).toBeCalled();
        expect(loginCard).toBeVisible();
    })
});
Run Code Online (Sandbox Code Playgroud)

组件在这里:导航栏:

"use client"

import React, { Dispatch, SetStateAction } from "react";
import { useRouter } from "next/navigation";

interface NavBarProps {
  setVisibleLogin?: Dispatch<SetStateAction<boolean>>; …
Run Code Online (Sandbox Code Playgroud)

next.js react-testing-library ts-jest

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

在 Jest 中模拟 Firebase 管理员时出错:“TypeError:admin.firestore 不是函数”

我有一个函数可以通过 Admin SDK 处理与 Cloud Firestore 的连接。我知道该功能工作正常,因为应用程序连接并允许写入数据库。

现在我正在尝试用 Jest 测试这个功能。为了避免在此函数范围之外进行测试,我模拟了 firebase-admin Node 模块。但是,我的测试失败并出现错误“TypeError:admin.firestore不是函数”。

我的函数和测试都是用 TypeScript 编写的,通过 ts-jest 运行,但我不认为这是 TypeScript 错误,因为 VS Code 没有任何抱怨。我相信这是 Jest 自动模拟的问题。

admin.firebase()是一个有效的调用。TypeScript 定义文件将其定义为function firestore(app?: admin.app.App): admin.firestore.Firestore;

我已经阅读了 Jest 文档,但我不明白如何解决这个问题。

这是我的功能:

// /src/lib/database.ts

import * as admin from "firebase-admin"

/**
 * Connect to the database
 * @param key - a base64 encoded JSON string of serviceAccountKey.json
 * @returns - a Cloud Firestore database connection
 */
export function connectToDatabase(key: string): FirebaseFirestore.Firestore {
  // irrelevant code to …
Run Code Online (Sandbox Code Playgroud)

javascript firebase typescript jestjs ts-jest

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

如何使用 Jest 和 React 测试库测试输入的占位符

我使用搜索栏组件构建了一个简单的反应应用程序。搜索栏组件包含一个输入。为了进行测试,我使用 Jest 和 React 测试库。我想编写一个测试,测试当在输入的值中输入某些内容时,输入的占位符是否消失。

Searchbar.test.tsx

test("SearchBar placeholder gets replaced by search string", () => {
  const handleSearchRequest = jest.fn();
  render(<SearchBar searchInputValue="Hello World"/>);
  
  const searchInput = screen.getByPlaceholderText("Search");

  expect(searchInput).toBeFalsy();                  //test fails
  // expect(searchInput).not.toBeInTheDocument();   //test fails
  // expect(searchInput).toBeNull();                //test fails
});
Run Code Online (Sandbox Code Playgroud)

搜索栏.tsx

      <Input
        placeholder="Search"
        value={currentValue}
      />
Run Code Online (Sandbox Code Playgroud)

我应该如何编写这个测试有什么想法吗?

react-testing-library ts-jest

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

如何使用 Jest 模拟拒绝承诺

我在做什么?

我正在学习 Nestjs 课程,其中有一些单元测试。我编写了这个测试来检查存储库类中的signUp方法。问题是,为了触发异常,该行user.save()应该返回一个承诺拒绝(模拟写入数据库的一些问题)。我尝试了几种方法(见下文),但没有一个有效。

问题

结果是测试成功了,但是有一个unhandled Promise rejection. 这样,即使我断言它not.toThow()会以相同的方式成功unhandled Promise rejection

(node:10149) UnhandledPromiseRejectionWarning: Error: expect(received).rejects.toThrow()

Received promise resolved instead of rejected
Resolved to value: undefined
(Use `node --trace-warnings ...` to show where the warning was created)
Run Code Online (Sandbox Code Playgroud)

我如何让它正确拒绝承诺?

代码

下面是我的测试代码和被测函数。

import { ConflictException } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { UserRepository } from './user.repository';

describe('UserRepository', () => {
  let userRepository: UserRepository;

  let authCredentialsDto: AuthCredentialsDto …
Run Code Online (Sandbox Code Playgroud)

unit-testing promise jestjs nestjs ts-jest

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

如何使用 ts-jest 和 ts-node 使用 rootDir 配置 typescript

我有这个设置:

// tsconfig.json

{
  "compilerOptions": {
    "rootDir": "src",
  ...
}

...

//jest.config.ts

...
globals: {
  'ts-jest': {
    tsconfig: {
      rootDir: '.'
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行 jest 时,我收到一个发出错误,指出打字稿文件需要位于根目录下,似乎这个“rootDir”编译器选项被忽略了。

我不希望我的 /test 或我的配置位于 /src 下,并且我不希望它被编译到 /lib 或被发出。

我也无法排除它,exclude因为这样它也排除了项目外部的 .ts 文件的类型,这使得使用 ts-node 非常困难。

typescript jestjs ts-node ts-jest

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

如何设置 Jest w/ESM 以识别 node_modules 中的非 cjs 模块

已经成功设置了 jest/esm,但是偶尔会发布一个模块,该main模块module在其package.json. 这会导致玩笑错误,例如使用uuid 模块

/repo/path/node_modules/uuid/dist/esm-browser/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
                                                                                      ^^^^^^
SyntaxError: Unexpected token 'export'

Run Code Online (Sandbox Code Playgroud)

我可以看到这是由 中的键dist/esm-browser/index.js指定的文件。modulepackage.json

如何配置 Jest w/ESM 来处理这些情况,其中 node_modules 中的内容是 ESM?

笑话配置:

{
    "resetMocks": true,
    "testEnvironment": "jsdom",
    "testMatch": [
      "**/src/**/*.(spec|test).[tj]s?(x)"
    ],
    "preset": "ts-jest/presets/default-esm",
    "extensionsToTreatAsEsm": [
      ".ts",
      ".tsx"
    ],
    "globals": {
      "ts-jest": {
        "useESM": true
      }
    },
    "globalSetup": "<rootDir>/jest/setup.cjs",
    "globalTeardown": "<rootDir>/jest/teardown.cjs",
    "watchPathIgnorePatterns": [
      "<rootDir>/.tmp"
    ],
    "moduleNameMapper": {
      "^~/(.*)$": "<rootDir>/src/$1",
      "^~components/(.*)$": "<rootDir>/src/components/$1",
      "^~util/(.*)$": "<rootDir>/src/util/$1", …
Run Code Online (Sandbox Code Playgroud)

javascript node.js jestjs es6-modules ts-jest

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

在 Next.js 上使用 jest 找不到模块错误

您好,我在 nextjs 应用程序上使用 jest 时遇到一些麻烦,当我使用脚本“jest”时,我总是执行失败,结果如下

\n
\n FAIL  __tests__/index.test.tsx\n  \xe2\x97\x8f Test suite failed to run\n\n    Cannot find module '@components/Layout' from 'pages/404.tsx'\n\n    Require stack:\n      pages/404.tsx\n      __tests__/index.test.tsx\n\n    > 1 | import { Layout } from '@components/Layout'\n        |                                            ^\n      2 | import { ContainerChild } from '@components/Container'\n      3 | import { Button } from '@castia/components.ui.button'\n      4 | import Image from 'next/image'\n\n      at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:491:11)\n      at Object.<anonymous> (pages/404.tsx:1:44)\n\nTest Suites: 1 failed, 1 total\nTests:       0 total\nSnapshots:   0 total\nTime:        1.31 s\nRan all test suites.\n\n
Run Code Online (Sandbox Code Playgroud)\n

这是我的测试文件 …

typescript reactjs jestjs next.js ts-jest

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

如何提高React测试库速度?

我注意到我的第一个测试需要 6 秒才能运行,但是,它非常简单。它检查 Card 组件是否成功渲染传递的子组件:

describe('Card component', () => {
  test('renders children', () => {
    const testString = 'TEST';

    const TestCardChild: React.FC = () => {
      return <p>{testString}</p>;
    };

    render(
      <Card>
        <TestCardChild />
      </Card>
    );

    expect(screen.getByText(testString));
  });
});
Run Code Online (Sandbox Code Playgroud)

我在另一台具有几乎相同规格的机器上运行了测试,它在几毫秒内运行。您知道为什么会发生这种情况吗?我应该为 VS code 分配更多 RAM,还是应该为 React 测试库应用任何设置?

感谢致敬

unit-testing reactjs react-testing-library ts-jest

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