标签: ts-jest

使用 TypeScript 和 ES 模块的 Jest 无法从 commonjs 模块导入“命名导入”

使用 TS,可以使用语法导入 CJS 模块的导出,就好像它们被命名为 ES 模块导出一样,例如:

import { sync } from 'glob';
Run Code Online (Sandbox Code Playgroud)

但是,对于 Jest 和 ES 模块,当这种导入方式位于测试文件或测试文件的依赖项中时,它会显示SyntaxError: The requested module 'glob' does not provide an export named 'sync'.

逐一检查所有内容并将它们更改为import glob from 'glob';然后调用glob.sync()似乎可行,但是当将一些遗留内容从另一个测试运行程序迁移到 Jest 时,这可能不是一个选择,因为代码库中有很多这样的导入。

转载于此: https: //github.com/themaskedavenger/tsjestcjerepro

运行 jest:(如https://jestjs.io/docs/ecmascript-modulesnode --experimental-vm-modules node_modules/jest/bin/jest.js中所述),并使用 Jest 配置:

  resetMocks: true,
  testEnvironment: "node",
  testMatch: [
    "**/src/**/*.(spec|test).[tj]s?(x)"
  ],
  preset: 'ts-jest/presets/default-esm',
  transform: {},
  'extensionsToTreatAsEsm': [".ts", ".tsx"],
  globals: {
    'ts-jest': {
      useESM: true,
      tsconfig: {
        allowSyntheticDefaultImports: true,
        declaration: true,
        esModuleInterop: …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs babel-jest es6-modules ts-jest

5
推荐指数
0
解决办法
1392
查看次数

如何在 Jest 中模拟 NestJS 内置 Logger

我有一个控制器,它通过控制器构造函数中的依赖项注入使用 NestJS 内置 Logger:

  constructor(private readonly logger: Logger) 
Run Code Online (Sandbox Code Playgroud)

我希望能够在 Jest 测试中模拟它,以查看在日志记录期间调用了哪些方法以及使用哪些参数。我尝试了这个语法:

providers[{
    provide: Logger,
    useValue: {
      log: jest.fn(),
    }
}]
Run Code Online (Sandbox Code Playgroud)

在这种情况下,这一行:

    expect(Logger).toHaveBeenCalledTimes(1);
Run Code Online (Sandbox Code Playgroud)

返回: 匹配器错误:接收到的值必须是模拟或间谍函数

任何帮助将不胜感激!

nestjs ts-jest

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

使用 jest 模拟外部库调用

玩笑和反应代码测试的新手。我正在测试一个文件,该文件从react-native-base64导入base64并解码从useEffect中的后端系统获取的值。下面是示例代码。

import base64 from "react-native-base64";
 
  const xyzWork = async () => {
    const value = await - fetch data from backend
    const decodedValue = base64.decode(value);
    ...
    ...
    ...
  }

  useEffect(() => {
    xyzWork();
  }, []);


  return <div><SomeComponent /></div>;
Run Code Online (Sandbox Code Playgroud)

我在使用笑话测试此代码时遇到困难。我尝试了多种方法来测试相同的结果,但由于多个错误而失败。

有些方法,以同样的方式导入base64并像这样模拟。 base64.decode = jest.fn(()=> "testParsedValue");

尝试模拟整个库本身,const mockedLib = jest.mock("react-native-base64", () => jest.fn());然后模拟该变量的 base64,但似乎没有任何效果。

任何帮助,将不胜感激!谢谢!

javascript unit-testing reactjs jestjs ts-jest

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

无法运行组件的 Jest 测试(无法加载 html 文件)

我无法在我的组件上运行 Jest 测试,因为它无法加载 html 文件。我收到此错误:

Error: Error: connect ECONNREFUSED 127.0.0.1:80
Run Code Online (Sandbox Code Playgroud)

其次是:

Unhandled Promise rejection: Failed to load landing.component.html
Run Code Online (Sandbox Code Playgroud)

运行非组件测试就可以了。

这是我的jest.config.js

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  preset: "jest-preset-angular",
  testEnvironment: "jsdom",
  setupFilesAfterEnv: ["<rootDir>/setup-jest.ts"],
  globals: {
    "ts-jest": {
      tsconfig: "<rootDir>/tsconfig.spec.json",
      stringifyContentPathRegex: "\\.(html|svg)$",
    },
  },
  snapshotSerializers: [
    "jest-preset-angular/build/serializers/html-comment",
    "jest-preset-angular/build/serializers/ng-snapshot",
    "jest-preset-angular/build/serializers/no-ng-attributes",
  ],
  moduleDirectories: ["node_modules", "."],
  testMatch: ["**/+(*.)+(spec|test).+(ts|js)?(x)"],
  transform: {
    "^.+\\.(ts|js|html)$": "ts-jest",
  },
  resolver: "@nrwl/jest/plugins/resolver",
  moduleFileExtensions: ["ts", "js", "html"],
  coverageReporters: ["html"],
};
Run Code Online (Sandbox Code Playgroud)

我的setup-jest.ts

import 'jest-preset-angular/setup-jest';
Run Code Online (Sandbox Code Playgroud)

和我的tsconfig.spec.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": { …
Run Code Online (Sandbox Code Playgroud)

jestjs angular ts-jest

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

Typescript + jest 无法在模块外部使用 import 语句

我几乎搜索了谷歌中的每个主题,但看起来它随着配置和版本的变化而变化。

我在导入 ES6 时遇到问题。我做了我能做的一切,我检查了 ts-jest 和 jest github issues 以及整个 stackoverflow,但无法完成。也许我忘记了什么?我仍然收到此错误: SyntaxError: Cannot use import statement outside a module

我真的不知道还能做什么...

我的 babel.config.js

module.exports = api => {
    const isTest = api.env('test');
    // You can use isTest to determine what presets and plugins to use.

    return {
        presets: [
            [
                '@babel/preset-env',
                '@babel/preset-typescript',
                {
                    targets: {
                        node: 'current',
                    },
                },
            ],
        ],
        env: {
            test: {
                plugins: [
                    "transform-es2015-modules-commonjs"
                ]
            }
        }
    };
};
Run Code Online (Sandbox Code Playgroud)

笑话配置.js

module.exports = {
    preset: 'ts-jest',
    rootDir: "./", …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs ts-jest

5
推荐指数
0
解决办法
974
查看次数

TS2307:找不到模块“@jest/globals”或其相应的类型声明

我遇到错误 TS2307:在导入默认测试套件的值时找不到模块“@jest/globals”或其相应的类型声明(但它成功通过

import { describe, expect, test } from '@jest/globals'

describe('Example test', () => {
    test('something', () => {
        expect('').toBeFalsy()
    })
})
Run Code Online (Sandbox Code Playgroud)

我的package.json

"devDependencies": {
        "@types/jest": "^27.0.3",
        "@types/node": "^16.11.11",
        ...
        "typescript": "^4.4.4",
    },
    "optionalDependencies": {
        ...
    },
    "dependencies": {
        "@jest/globals": "^27.4.2",
        "babel-preset-jest": "^27.4.0",
        ...
    }
}

Run Code Online (Sandbox Code Playgroud)

有人可以帮助我吗?

jestjs ts-jest

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

TypeScript 与 Jest 无法检测到库

Jest 似乎无法获取导入的库。我一直在阅读相关内容并尝试各种选择。其中之一就是这个。然而它们似乎都不起作用。

\n
//xyz.ts\n\n..\n/* eslint-disable */\nimport * as csv from \'csv-stringify/sync\';\n/* eslint-enable */\n..\n
Run Code Online (Sandbox Code Playgroud)\n

运行 Jest 后:

\n
Test suite failed to run\n\n    Cannot find module \'csv-stringify/sync\' from \'xyz.ts\'\n
Run Code Online (Sandbox Code Playgroud)\n

正在使用的库 - https://csv.js.org/stringify/

\n

我怀疑我做错了什么,因为如果我不禁用它的检查,即使 ESLint 也会抱怨这一点。

\n
 Unable to resolve path to module \'csv-stringify/sync\'  import/no-unresolved\n
Run Code Online (Sandbox Code Playgroud)\n

图书馆的结构:

\n

csv-stringify 包

\n

此外,如果我尝试导入为

\n
import * as csv from \'csv-stringify/lib/sync\';\n
Run Code Online (Sandbox Code Playgroud)\n

然后我在运行 Jest 后收到此错误

\n
Test suite failed to run\n\n    Jest encountered an unexpected token\n\n    Jest failed to parse …
Run Code Online (Sandbox Code Playgroud)

csv typescript ts-jest

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

节点 + ts-jest + ESM,jest.mock 什么都不做

我正在使用ts-jestESM 导入nodejs
问题是我的jest.mock不工作,它不是嘲笑。

import { jest } from "@jest/globals";

jest.mock("./helpers"); // I tried before or after import
import { fn } from "./helpers";


describe("SimpleTest", () => {
  it("should work", () => {
    console.log(fn); // => defined
    console.log(fn.mockReturnValue); // => /!\ UNDEFINED, fn is not a jest mock.
  });
});
Run Code Online (Sandbox Code Playgroud)

我的笑话配置:

export default {
  preset: "ts-jest/presets/default-esm",
  extensionsToTreatAsEsm: [".ts"],
  globals: {
    "ts-jest": {
      useESM: true,
    },
  },
}
Run Code Online (Sandbox Code Playgroud)

我使用的命令:
node --experimental-vm-modules --experimental-specifier-resolution=node $(yarn bin jest)

我正在使用节点 …

node.js typescript jestjs ts-jest

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

如何在 jest.spyOn 上正确设置类型?

我在我的打字稿玩笑测试中写了以下内容:

beforeEach(() => {
    jest
      .spyOn<MyParentClass, any>(MyChildClass.prototype, "doRequest")
      .mockImplementation(async function (this:MyChildClass) {
              /// do my mock
      }  as () => never);
Run Code Online (Sandbox Code Playgroud)

添加该部分as () => never是为了跳过异步上的类型检查器错误,表示

Argument of type '(this:MyChildClass) => Promise<any>' is not assignable to parameter of type '() => unknown'
Run Code Online (Sandbox Code Playgroud)

我找不到改进以下内容的方法,将任何内容缩小为更精确的类型:.spyOn<MyParentClass, any>

根据定义

function jest.spyOn<T extends {}, M extends jest.NonFunctionPropertyNames<Required<T>>>(object: T, method: M, accessType: "get"): jest.SpyInstance<Required<T>[M], []> (+3 overloads)
Run Code Online (Sandbox Code Playgroud)

我尝试了其他可能适合的类型,但没有成功......

测试运行成功,我能够监视和模拟,只是想知道如何编写更好的打字定义。

mocking typescript ts-jest

5
推荐指数
0
解决办法
2450
查看次数

如何模拟 Identity Platform Authentication 以触发 beforeCreateHandler

我有一个谷歌云函数,我在谷歌身份平台的触发器中运行beforeCreate它,如下所示:

import * as gcipCloudFunctions from "gcip-cloud-functions";
const authClient = new gcipCloudFunctions.Auth();
const beforeCreate = authClient.functions().beforeCreateHandler((user, context) => {
 console.log("Hello world");
 });
export default beforeCreate;
Run Code Online (Sandbox Code Playgroud)

我如何创建笑话测试来模拟此事件?或者如何创建测试来执行此功能?

阻塞函数

unit-testing node.js google-cloud-functions ts-jest google-cloud-identity

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