首页 > 解决方案 > Jest 和 Typescript - 在函数中模拟 const

问题描述

这里是 Jest 的新手,不知道我会如何做到这一点:

假设我有一些函数包含const我设置为特定类型 ( newArtist) 的函数:

export class myTestClass {
    async map(document: string) {
        const artist: newArtist = document.metadata.artist;
        ...
        }
}

除此之外,我还有:

export interface newArtist {
    name: string;
    title: string;
}

现在,当我编写测试时,如果我确实说以下内容:

it("My example test", async () => {
    const result: any = await new myTestClass(__context()).map({
        name: "An Artist"
        title: null
    });
        ...
}

测试将失败,因为title设置为 null。为了测试的目的,我需要该界面有点不同 - 基本上是这样的:

export interface newArtist {
    name: string;
    title: string | null;
}

我怎样才能做到这一点?我见过模拟类,但这是否意味着我最终会复制/粘贴所有map功能代码?

任何帮助表示赞赏。

谢谢。

标签: typescriptjestjs

解决方案


我不太清楚你想做什么。您提供的代码不正确。

对我来说,下面的代码适用于 typescript 和 jest。请提供更多信息。

index.ts

export interface INewArtist {
  name: string;
  title: string | null;
}

export interface IDocument {
  metadata: {
    artist: INewArtist;
  };
}

export class MyTestClass {
  constructor(private readonly ctx) {}
  public async map(document: IDocument) {
    const artist: INewArtist = document.metadata.artist;
  }
}

单元测试:

import { MyTestClass, IDocument } from './';

// tslint:disable-next-line: variable-name
const __context = () => {};

describe('MyTestClass', () => {
  it('My example test', async () => {
    const document: IDocument = {
      metadata: {
        artist: {
          name: 'An Artist',
          title: null
        }
      }
    };

    const result: any = await new MyTestClass(__context()).map(document);
  });
});

单元测试结果:

 PASS  src/stackoverflow/56847385/index.spec.ts
  MyTestClass
    ✓ My example test (3ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.396s

推荐阅读