英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论