mok*_* Lo 4 javascript node.js reactjs jestjs
我开始使用Jest测试我的代码,但我无法通过看似简单的测试。我只是想检查我从Maogoose数据库请求中收到的内容是否是一个对象。
该功能fetchPosts()有效,因为我将其与React前端连接在一起,并且可以正确显示数据。
这是我的功能fetchPosts():
module.exports = {
fetchPosts() {
return new Promise((resolve, reject) => {
Posts.find({}).then(posts => {
if (posts) {
resolve(posts)
} else {
reject()
}
})
})
}
}
Run Code Online (Sandbox Code Playgroud)
而我的测试:
it('should get a list of posts', function() {
return posts.fetchPosts().then(result => {
expect(typeof result).toBe('object')
})
})
Run Code Online (Sandbox Code Playgroud)
这使测试失败,Jest说
' 超时-在jest.setTimeout指定的5000ms超时内未调用异步回调。'
问题:如何使该测试通过?
你可以期望异步结果使用resolves,如所示的玩笑文档中。
在您的情况下:
it('should get a list of posts', function() {
const result = posts.fetchPosts();
expect(result).resolves.toEqual(expect.any(Object));
})
Run Code Online (Sandbox Code Playgroud)
…虽然我怀疑您的帖子列表实际上是一个数组,所以您可能想要这样:
it('should get a list of posts', function() {
const result = posts.fetchPosts();
expect(result).resolves.toEqual(expect.any(Array));
})
Run Code Online (Sandbox Code Playgroud)
另一个提示:您无需将主体包装fetchPost在其他promise中,只需返回您从中获得的promise Posts.find并then为其添加a ,如下所示:
module.exports = {
fetchPosts() {
return Posts.find({}).then(posts => {
if (posts) {
return posts;
}
throw new Error('no posts'); // this will cause a promise rejection
})
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5810 次 |
| 最近记录: |