标签: 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
查看次数

Jest &amp; TypeScript:VS Code 找不到名字

我正在将 Jest 与 TypeScript 一起使用。尽管我的代码可以工作并且我可以构建我的项目,但 Visual Studio Code 会为所有 Jest 方法(describe()test()...)抛出该错误:

Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.ts(2582)
Run Code Online (Sandbox Code Playgroud)

我有srctests分开的目录。我遵循了在 Internet 上找到的配置,但它没有改变任何东西,我错过了什么?到目前为止唯一的方法是将我的tests文件夹包含在 中的include设置中tsconfig,这很糟糕,因为它内置在dist目录中。

安装的开发依赖项: jest ts-jest @types/jest

tsconfig.json

{
  "compilerOptions": {
    "sourceMap": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowJs": true,
    "jsx": "react",
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"], …
Run Code Online (Sandbox Code Playgroud)

typescript tsconfig jestjs visual-studio-code ts-jest

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

如何在 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
查看次数

如何模拟尚不存在的节点模块?

no-such-module.ts

declare module 'no-such-module' {
    export function sum(a: number, b: number): number;
}
Run Code Online (Sandbox Code Playgroud)

总和

import { sum } from 'no-such-module';

export const func = (a: number, b: number) => sum(a, b);
Run Code Online (Sandbox Code Playgroud)

样本.test.ts

jest.mock('no-such-module');
const { sum } = require('no-such-module');

sum.mockImplementation((a,b) => a+b);

describe('sample test', () => {
    it('should pass', () => {
        expect(sum(1, 2)).toBe(3);
    });
});
Run Code Online (Sandbox Code Playgroud)

错误

Cannot find module 'no-such-module' from 'sample.test.ts'

    > 1 | jest.mock('no-such-module');
        |      ^
      2 | const { sum } = require('no-such-module');
      3 | 
      4 …
Run Code Online (Sandbox Code Playgroud)

typescript jestjs ts-jest

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

monorepo 中带有 tyescript 的玩笑不适用于根文件夹之外的依赖项

我将 Jest 与 Typescript 结合使用。我想创建一个单一存储库。我的文件夹结构是:

fe
|-app1
|--.jest.config.ts
|--tsconfig.json
|-shared
|--dummyData.ts
Run Code Online (Sandbox Code Playgroud)

我想要一个单元测试来app1访问shared文件夹中的一些数据。

fe/app1/demo.spec.ts:

import { someData } from '@shared/dummyData' //<--HERE: the alias is works, but jest can not understand "export" keyword

descrube('demo' () => {
  it('demo test', () => {
    expect(someData).toBe('DUMMY'));
  })
})
Run Code Online (Sandbox Code Playgroud)

fe/shared/dummyData.ts:

export const someData = 'DUMMY';
Run Code Online (Sandbox Code Playgroud)

问题是 jest 抛出错误:

Jest encountered an unexpected token
{"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export const someData = 'DUMMY';
                                                                                        ^^^^^^
Run Code Online (Sandbox Code Playgroud)

据我了解,它无法解析由 ts 和 babel 生成的 typescript 或 es6 模块。当文件夹位于 inside …

javascript typescript jestjs monorepo ts-jest

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