如何在我的Jest单元测试中模拟一个TypeScript枚举?

huangapple go评论60阅读模式
英文:

How do I mock a TypeScript enum in my Jest unit tests?

问题

我想在我的单元测试中模拟一个枚举类型。我的枚举类型如下:

enum OriginalEnum {
START = 'start',
EXPORT = 'export',
SEARCH = 'search',
END = 'end'
}


`START` 值始终保持不变,以及 `END` 值,但中间的枚举选项会随时间而变化。它们代表着“新”功能,会被突出显示。过一段时间,一个现有的枚举选项可能会被移除并替换为另一个选项。

我希望能够测试那些与此枚举类型一起工作的类是否正确地来回跳转,而不必在中间的枚举选项被添加/移除时每次更新我的单元测试。

因此,我的测试应该使用另一个枚举类型,看起来像这样:

enum MockedEnum {
START = 'start',
NAME_OF_FIRST = 'nameOfFirst',
NAME_OF_SECOND = 'nameOfSecond',
END = 'end'
}

英文:

I want to mock an enum in my unit tests. My enum looks like this:

enum OriginalEnum {
	START = 'start',
	EXPORT = 'export',
	SEARCH = 'search'
	END = 'end'
}

The START value always stays in place, as well as the END value, but the in-between enum options change over time. They represent "new" features that are highlighted. After a while an existing enum option might be removed and replaced by another one.

What I want is to be able to test that the classes that work with this enum are jumping back and forth correctly, without having to update my unit tests every time one of the in-between enum options is added/removed.

So, my tests should use another enum, that looks like this:

enum MockedEnum {
	START = 'start',
	NAME_OF_FIRST = 'nameOfFirst',
	NAME_OF_SECOND = 'nameOfSecond',
	END = 'end'
}

答案1

得分: 2

我找到的解决方案依赖于这段代码:

jest.mock('./../../models/original-enum.ts', () => ({
	OriginalEnum: jest.requireActual('./../mocks/mocked-enum').MockedEnum 
}));

放置在单元测试文件顶部时,它将原枚举的内容设置为模拟枚举,但仅适用于该测试文件。

您仍然可以使用 import { MockedEnum } from './../mocks/mocked-enum' 导入模拟枚举,以便在特定测试中使用模拟枚举选项。

英文:

The solution that I found relies on this piece of code:

jest.mock('./../../models/original-enum.ts', () => ({
	OriginalEnum: jest.requireActual('./../mocks/mocked-enum').MockedEnum 
}));

When put at the top of a unit tests file, it sets the contents of the original enum equal to the mocked enum, but only for that test file.

You can still import the mocked enum using import { MockedEnum } from './../mocks/mocked-enum', so that you can work with the mocked enum options inside specific tests.

huangapple
  • 本文由 发表于 2023年5月29日 17:56:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356354.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定