标签: ts-jest

Typeorm 装饰器不是函数

我有以下要测试的控制器:

class Album {
  public static getAlbums(): Promise<AlbumModel[]> {
    return getRepository(AlbumModel).find({ relations: ['pictures'] });
  }
}
Run Code Online (Sandbox Code Playgroud)

这与模型相关联,我正在使用带有装饰器的 typeorm。这就是我使用 Jest 时问题的来源

import { Entity, PrimaryGeneratedColumn, Column, JoinTable, ManyToMany } from 'typeorm';
import { PicturesModel } from '../pictures/pictures.model';

@Entity({
  name: 'T_ALBUM_AL',
  synchronize: true,
})
export class AlbumModel {
  @PrimaryGeneratedColumn({
    name: 'AL_id',
  })
  id: number;

  @Column({
    name: 'AL_name',
  })
  name: string;

  @ManyToMany(() => PicturesModel, (picture: PicturesModel) => picture.id)
  @JoinTable({
    name: 'TJ_PICTURE_ALBUM_PA',
    joinColumn: {
      name: 'AL_id',
      referencedColumnName: 'id',
    },
    inverseJoinColumn: {
      name: 'PI_id',
      referencedColumnName: …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs typeorm ts-jest

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

使用带有 lit-html 的打字稿编写测试时出现“语法错误:无法在模块外使用导入语句”

我使用 typescript 用lit-html编写一个简单的演示:

import {html, TemplateResult} from 'lit-html';

export default function sayHello(name: string): TemplateResult {
  return html`<h1>Hello ${name}</h1>`;
}
Run Code Online (Sandbox Code Playgroud)

并使用 jest 编写一些简单的测试:

import sayHello from "./sayHello";
import {render} from "lit-html";

beforeEach(() => {
  render('', document.body);
})

describe('sayHello', () => {
  it('says hello', () => {
    render(sayHello('world'), document.body);
    const component = document.querySelector('h1');
    expect(component).toBeDefined();
  })
})
Run Code Online (Sandbox Code Playgroud)

我的“jest.config.js”是:

module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'jsdom',
}

Run Code Online (Sandbox Code Playgroud)

但是当我用 运行测试时jest,我得到了这样的错误:

FAIL  src/sayHello.test.ts
  ? Test suite failed to run

    Jest encountered an …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs es6-modules lit-html ts-jest

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

React Jest 测试无法使用 ts-jest 运行 - 在导入的文件上遇到意外标记

我是测试 React/Typescript 应用程序的新手。我想对我的 React 组件进行单元测试,因为我根本不满足于开发没有测试的应用程序。该应用程序本身运行良好,只是无法在测试模式下运行。

命令(别名react-scripts test):

yarn test
Run Code Online (Sandbox Code Playgroud)

输出:

yarn test
Run Code Online (Sandbox Code Playgroud)

我对@amcharts/amcharts4图书馆有依赖性。虽然Feature页面不使用amCharts,但该库用于其他页面。

Feature页面的简单测试代码:

import * as React from 'react';
import { create } from 'react-test-renderer';
import Feature from "./Feature";

describe('Feature page component', () => {
  test('matches the snapshot', () => {
    const feature = create(
      <Feature />,
    );
    expect(feature.toJSON()).toMatchSnapshot();
  });
});
Run Code Online (Sandbox Code Playgroud)

Feature我的功能性 React 组件 (TSX)在哪里?它是一个由其他组件组成的页面。

在阅读了类似的问题后,我怀疑我的应用程序配置有问题。所以这是我的配置:

.babelrc

{
  "presets": ["airbnb"]
}
Run Code Online (Sandbox Code Playgroud)

tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "jsx": "preserve", …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs react-test-renderer ts-jest

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

运行玩笑测试时无法附加调试器

我无法在运行玩笑测试时附加 VS Code 调试器。我尝试使用launch.json找到的不同替代方案配置文件,但它们总是失败并显示以下错误消息,抱怨 node_modules 文件夹中的文件:

Debugger attached.
Waiting for the debugger to disconnect...
local\path\to\node_modules\.bin\jest:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^

SyntaxError: missing ) after argument list
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)      
    at internal/main/run_main_module.js:17:47
Run Code Online (Sandbox Code Playgroud)

我的package.json文件具有以下配置:

Debugger attached.
Waiting for the debugger to disconnect...
local\path\to\node_modules\.bin\jest:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^

SyntaxError: missing ) after argument list
    at …
Run Code Online (Sandbox Code Playgroud)

node.js typescript jestjs ts-node ts-jest

7
推荐指数
2
解决办法
2821
查看次数

如何使 ts-jest 使用导入中导入的 js 文件的导入/导出语法?

jest无法导入我的导入,这导致命令在文件的第一行npm run test失败。对于本示例来说,是本地文件,而不是节点模块。我可以更改为并更改导入,但这不是解决方案。SyntaxError: Unexpected token 'export'bar.tsfoo.jsfoo.jsfoo.tsbar.ts

我的src文件夹中的文件:

  • foo.js:
export const magicNumber = 42; 
Run Code Online (Sandbox Code Playgroud)
  • bar.ts:
import { magicNumber } from './foo.js';

export const secondMagicNumber = magicNumber / 2; 
Run Code Online (Sandbox Code Playgroud)
  • bar.test.ts:
import { secondMagicNumber } from './bar';
import assert from 'assert';

it('should work', function() {
    assert.strictEqual(secondMagicNumber, 21);
});
Run Code Online (Sandbox Code Playgroud)

文件夹中的文件:

  • jest.config.js:
export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
};
Run Code Online (Sandbox Code Playgroud)
  • package.json:
{
  "name": "testing-with-jest",
  "version": "1.0.0",
  "description": "",
  "scripts": …
Run Code Online (Sandbox Code Playgroud)

javascript node.js typescript jestjs ts-jest

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

导入反应图时,Jest 因“self is not Defined”而失败

我正在尝试创建一个与 npm 依赖项交互的基本笑话测试:react-diagrams

失败的测试

import { DiagramModel } from '@projectstorm/react-diagrams'

test('importing react diagrams', () => {
    let x = DiagramModel
});
Run Code Online (Sandbox Code Playgroud)

简单地引用该类DiagramModel会导致此错误:

    ReferenceError: self is not defined

    > 1 | import { DiagramModel } from '@projectstorm/react-diagrams'
        | ^
      2 |
      3 | test('importing react diagrams', () => {
      4 |     let x = DiagramModel

      at Object.<anonymous> (node_modules/@projectstorm/react-diagrams/dist/index.umd.js:1:331)
      at Object.<anonymous> (tests/DiagramModel.test.ts:1:1)
Run Code Online (Sandbox Code Playgroud)

其他测试工作正常,并且依赖项在其他地方捆绑时工作正常。

笑话配置.js

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

包.json

"jest": "^26.6.3",
"ts-jest": "^26.5.2",
...
Run Code Online (Sandbox Code Playgroud)

我有什么想法可以解决这个问题吗? …

reactjs jestjs ts-jest

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

如何在 Angular Nx 存储库中使用 Jest 测试 Swiper 库?

我有一个 Nx 存储库,其中包含 Angular 应用程序和 Jest 作为测试框架。该应用程序有一个使用Swiper 的组件库的组件。当尝试测试该组件时,我收到以下错误消息:

\n
  \xe2\x97\x8f Test suite failed to run\n\n    Jest encountered an unexpected token\n\n    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.\n\n    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.\n\n    By default "node_modules" folder is ignored …
Run Code Online (Sandbox Code Playgroud)

jestjs angular ts-jest nrwl-nx swiper.js

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

如何使用 Jest 和 TypeScript 监视 ES6 类的方法?

我正在尝试监视我手动模拟的 ES6 类的方法。

我正在关注官方 Jest 文档,该文档仅针对 JavaScript。

这是我的代码:

// sound-player.ts
export default class SoundPlayer {
  foo: string

  constructor() {
    this.foo = 'bar'
  }

  playFile(fileName: string) {
    console.log(`Playing sound file: ${fileName}`)
  }
}
Run Code Online (Sandbox Code Playgroud)
// __mocks__/sound-player.ts
export const mockPlayFile = jest.fn()

const mock = jest.fn().mockImplementation(() => {
  return { playFile: mockPlayFile }
})

export default mock
Run Code Online (Sandbox Code Playgroud)
// sound-player-consumer.ts
import SoundPlayer from './sound-player'

export default class SoundPlayerConsumer {
  soundPlayer: SoundPlayer

  constructor(soundPlayer: SoundPlayer) {
    this.soundPlayer = soundPlayer
  }

  playSomethingCool() {
    this.soundPlayer.playFile('something-cool.mp3')
  }
}
Run Code Online (Sandbox Code Playgroud)
// …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs ts-jest

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

Jest 在工作区中找不到模块

我有一个在工作区中构建的 NPM 项目:

proj/
+-node_modules/
+-packages/
  +-pkg1/
    +-src/
      |-c1.ts
      |-c1.test.ts
    |-package.json
    |-jest.config.js
  +-pkg2/
    +-src/
      |-c2.ts
    |-package.json
+-apps/
|-package.json
Run Code Online (Sandbox Code Playgroud)

该项目的package.json

{
  "name": "proj",
  "scripts": {
    ...
    "test:pkg1": "npm test -w packages/pkg1",
  },
  "workspaces": [
    "packages/*",
    "apps/*"
  ]
}
Run Code Online (Sandbox Code Playgroud)

里面:package.jsonpkg1

{
  "name": "@proj/pkg1",
  "scripts": {
    ...
    "test": "jest --config=jest.config.js",
  },
  "devDependencies": {
    "@types/pegjs": "0.10.3",
    "@types/jest": "29.1.1",
    "ts-loader": "9.3.1",
    "typescript": "4.8.3",
    "webpack": "5.74.0",
    "webpack-cli": "4.10.0",
    "jest": "29.1.2",
    "ts-jest": "29.0.3"
  },
  "dependencies": {
    "@proj/pkg2": "1.0.0"
  }
}
Run Code Online (Sandbox Code Playgroud)

测试文件c1.test.ts …

npm jestjs ts-jest npm-workspaces

7
推荐指数
0
解决办法
914
查看次数

使用 Angular-jest-preset 在 Angular 9 中设置 Jest 时出现问题

我目前正在使用 jest-preset-Angular 版本 9 在 Angular 9 中设置 Jest,代码运行但出现以下错误:

TypeError: Cannot read property 'ngModule' of null

不知道如何调试。

在此输入图像描述

这是我的 jest.config.json

{
"preset": "jest-preset-angular",
"setupFilesAfterEnv": [
    "<rootDir>/setup-jest.ts"
],
"transformIgnorePatterns": [
    "node_modules/(?!@ngrx|ngx-socket-io)" 
],
"transform": {
    "^.+\\.(ts|js|html)$": "ts-jest"
},
"testPathIgnorePatterns": [
    "<rootDir>/node_modules/",
    "<rootDir>/dist/",
    "<rootDir>/src/test.ts"
],
"modulePaths": ["<rootDir>"]
Run Code Online (Sandbox Code Playgroud)

}

和规格文件

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { myComponent } from './knowuser.component';

import 'zone.js';
import 'zone.js/dist/async-test.js';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/zone-testing';

describe('myComponent', () => {
  let component: myComponent;
  let fixture: ComponentFixture<myComponent>;

  beforeEach(async(() => { …
Run Code Online (Sandbox Code Playgroud)

jestjs angular ts-jest

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