簡體   English   中英

玩笑和打字稿-在函數中模擬const

[英]Jest and Typescript - Mocking a const in a function

Jest的新手在這里,不知道我該怎么做:

假設我有一些函數,其中包含一個已設置為特定類型的constnewArtist ):

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函數代碼?

任何幫助表示贊賞。

謝謝。

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

對我來說,以下代碼可與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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM