玩笑和打字稿-在函数中模拟const

时间:2019-07-02 07:28:49

标签: typescript jestjs

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函数代码?

任何帮助表示赞赏。

谢谢。

1 个答案:

答案 0 :(得分:0)

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

对我来说,以下代码可与打字稿和玩笑一起使用。请提供更多信息。

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
相关问题