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'.
我确定我遗漏了一些明显的东西,但此时我已经撞墙了。有人可以帮忙吗?
这是下面的演示代码,用于演示我在当前项目中遇到的失败。
它编译并运行,只是无法使用笑话进行编译,并出现以下错误
错误:错误 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) 当我使用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) 我有一个函数可以通过 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) 我使用搜索栏组件构建了一个简单的反应应用程序。搜索栏组件包含一个输入。为了进行测试,我使用 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)
我应该如何编写这个测试有什么想法吗?
我正在学习 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) 我有这个设置:
// 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 非常困难。
已经成功设置了 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) 您好,我在 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\nRun Code Online (Sandbox Code Playgroud)\n这是我的测试文件 …
我注意到我的第一个测试需要 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 测试库应用任何设置?
感谢致敬
ts-jest ×10
jestjs ×7
typescript ×5
javascript ×3
next.js ×2
reactjs ×2
unit-testing ×2
es6-modules ×1
firebase ×1
nestjs ×1
node.js ×1
promise ×1
ts-node ×1