【发布时间】:2021-03-16 20:14:08
【问题描述】:
我是 Jest 的新手,我正试图弄清楚如何在每次测试后重置测试对象。
当前代码
describe.only('POST request - missing entry', () => {
// newBlog is the "test" object
let newBlog = {
title: 'Test Title',
author: 'Foo Bar',
url: 'www.google.com',
likes: 100
}
test('sets "likes" field to 0 when missing', async () => {
delete newBlog.likes // propagates to next test
console.log(newBlog)
})
test('returns 400 error when "title" and "url" fields are missing', async () => {
console.log(newBlog)
})
})
目标:我正在使用 jest 编写测试来测试错误的 POST 请求。即我的 POST 请求会故意为每个测试缺少字段。
likes 字段将从第一个测试中省略,而title, url 字段将在第二个测试中丢失。目标是只编写一次newBlog 对象,而不是为每个测试重写对象。
问题 这里的主要问题是第一个测试的结果会传播到下一个测试,即当删除第一个测试的likes 字段时,它保持不变并开始第二个测试而没有@987654326 @字段。
我想知道如何为每个测试重置对象的内容。
尝试到目前为止,我尝试了几件事:
- 我使用
BeforeEach以下列方式重置newBlog:
beforeEach(() => {
let newBlog = {
title: 'Test Title',
author: 'Foo Bar',
url: 'www.google.com',
likes: 100
}
return newBlog
})
但是,上面的代码不起作用,因为newBlog 在不同的范围内,所以每个测试都不能识别newBlog 变量。
- 我还使用
AfterEach通过以下方式重置:
afterEach(() => {
jest.clearAllMocks()
})
这一次,它运行了,但给了我与第一个代码 sn-p 相同的结果。
我想知道如何为每个测试重置对象,因为 stackoverflow 中讨论的许多解决方案似乎都专注于重置 functions 而不是 objects。
提前感谢您的帮助。
【问题讨论】:
-
声明你的
beforeEach的newBlog变量otuside -
@DanielA.White 谢谢,这正是我所需要的!
标签: javascript testing jestjs