英文:
How do I reset my class after every test?
问题
以下是您要翻译的内容:
I would like to reset a class assigned to a const after every test.
In main.ts I have a class and assign it to a const:
我想在每次测试后重置分配给常量的类。
在 main.ts 中,我有一个类并将其分配给一个常量:
class MyClass {
// many properties and methods inside here
}
const myClass = new MyClass()
Now I would like to reset this to a fresh class after every test I run. This will be done with the built-in function `afterEach()` from jest. I tried to just assign it like this:
现在,我希望在运行每次测试后将其重置为一个新的类。这将使用 jest 的内置函数 `afterEach()` 来完成。我尝试像这样分配它:
main.myClass = new MyClass()
but TypeScript is complaining `Cannot assign to 'myClass' because it is a read-only property.`
但是 TypeScript 报错说“无法分配给 'myClass',因为它是一个只读属性。”
What is the proper way to do this?
有什么正确的方法可以做到这一点?
<details>
<summary>英文:</summary>
I would like to reset a class assigned to a const after every test.
In main.ts I have a class and assign it to a const:
class MyClass {
// many properties and methods inside here
}
const myClass = new MyClass()
Now I would like to reset this to a fresh class after every test I run. This will be done with the built in function afterEach() from jest. I tried to just assign it like this:
main.myClass = new MyClass()
but typescript is complaining `Cannot assign to 'myClass' because it is a read-only property.`
What is the proper way to do this?
</details>
# 答案1
**得分**: 1
因为你的代码中使用了 'const' 关键字:
```javascript
const myClass = new MyClass()
你可以将它重写为(在 TypeScript 中):
let myClass: myClass = new MyClass();
然后,当你想要重置它时,只需执行:
myClass = new MyClass();
英文:
It's because of 'const' keyword in your
const myClass = new MyClass()
You can rewrite it as (in typescript)
let myClass : myClass = new MyClass();
Then when you want to reset it you just do
myClass = new MyClass();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论