typescript - 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
功能代码?
任何帮助表示赞赏。
谢谢。
解决方案
我不太清楚你想做什么。您提供的代码不正确。
对我来说,下面的代码适用于 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
推荐阅读
- php - 使用 .htaccess 删除 .php 扩展名会重复我的页面吗?
- ios - 如何使用 UITableView 在列表中创建列表
- python - 将列表从 pandas 列附加到 python 列表
- c# - Xamarin Android 将小部件工具栏图标向右对齐
- django - Django filter queryset __in exact matching
- python - 数据框列 str 替换为列表
- latex - 未在 toc 中的参考文献后的附录和缺少图形标签
- ios - 在 Swift 4 中使用 KeyEnumerators
- javascript - 我可以将 DOM 节点从 iFrame 移动到父母的正文吗?
- python - NameError:名称“click_entry”未定义(Python)