【问题标题】:Jest and Typescript - Mocking a const in a functionJest 和 Typescript - 在函数中模拟 const
【发布时间】:2019-09-08 17:30:59
【问题描述】:

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

任何帮助表示赞赏。

谢谢。

【问题讨论】:

  • 你确定原因是关于null 和类型检查?对我来说,您传递的数据结构不相关:而不是具有 metadata 类型的 object 属性的 string,而是直接传递 object

标签: typescript jestjs


【解决方案1】:

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

对我来说,下面的代码适用于 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

【讨论】:

    猜你喜欢
    • 2021-04-05
    • 2020-04-24
    • 2020-06-06
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 2018-12-31
    相关资源
    最近更新 更多