如何在每次测试后重置我的课程?

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

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 &#39;myClass&#39; 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();

huangapple
  • 本文由 发表于 2023年2月27日 15:53:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577952.html
匿名

发表评论

匿名网友

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

确定