sel*_*ter 6 javascript testing jestjs
我是 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)
})
})
Run Code Online (Sandbox Code Playgroud)
目标:我正在使用 jest 编写测试来测试错误的 POST 请求。即我的 POST 请求将故意缺少每个测试的字段。
likes第一次测试中将省略字段,而title, url第二次测试中将缺少字段。目标是只编写newBlog一次对象,而不是为每个测试重写对象。
问题这里的主要问题是第一个测试的结果传播到下一个测试,即当删除likes第一个测试的字段时,它保持这样并在没有likes字段的情况下开始第二个测试。
我想知道如何重置每个测试的对象内容。
尝试到目前为止,我尝试了一些事情:
BeforeEach重置:newBlogbeforeEach(() => {
let newBlog = {
title: 'Test Title',
author: 'Foo Bar',
url: 'www.google.com',
likes: 100
}
return newBlog
})
Run Code Online (Sandbox Code Playgroud)
但是,上面的代码不起作用,因为newBlog它处于不同的范围内,因此每个测试都无法识别newBlog变量。
AfterEach通过以下方式重置: afterEach(() => {
jest.clearAllMocks()
})
Run Code Online (Sandbox Code Playgroud)
这次,它运行了,但给了我与第一个代码片段相同的结果。
我想知道如何为每个测试重置对象,因为 stackoverflow 中讨论的许多解决方案似乎侧重于重置函数而不是对象。
提前谢谢你的帮助。
小智 10
尝试这样的事情,在describe中声明变量并在beforeEach中重置它:
describe.only('POST request - missing entry', () => {
// newBlog is the "test" object
let newBlog;
beforeEach(() => {
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)
})
})
Run Code Online (Sandbox Code Playgroud)