使用Node的Jest测试-超时-在jest.setTimeout指定的5000ms超时内未调用异步回调

时间:2018-11-20 16:46:14

标签: 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()
                }
            })
        })
    }
}

我的测试:

it('should get a list of posts', function() {
    return posts.fetchPosts().then(result => {
        expect(typeof result).toBe('object')
    })
})

这使测试失败,Jest说

'超时-在jest.setTimeout指定的5000ms超时内未调用异步回调。'

  

问题:如何通过此考试?

3 个答案:

答案 0 :(得分:4)

您可以期望使用shown in the Jest documentation作为resolves的异步结果。

在您的情况下:

it('should get a list of posts', function() {
    const result = posts.fetchPosts();
    expect(result).resolves.toEqual(expect.any(Object));
})

…尽管我怀疑您的帖子列表实际上是一个数组,所以您可能想要这样:

it('should get a list of posts', function() {
    const result = posts.fetchPosts();
    expect(result).resolves.toEqual(expect.any(Array));
})

另一个提示:您不需要将fetchPost的主体包装在其他承诺中,只需返回从Posts.find获得的承诺并将then添加到像这样:

module.exports = {
    fetchPosts() {
        return Posts.find({}).then(posts => {
            if (posts) {
                return posts;
            } 
            throw new Error('no posts'); // this will cause a promise rejection
        })
    }
}

答案 1 :(得分:1)

如果您只是想增加超时时间,也可以通过设置

 jest.setTimeout(10000);

如果要更改描述块中所有测试的超时,可以在beforeEach中使用此语句;如果要更改单个测试,则可以在test / it / spec块中使用此语句。

答案 2 :(得分:0)

很有可能您根本没有从测试套件中获得DB的响应。测试套件可以调用导致不同调用的不同环境变量/配置。如果未返回任何响应,也可以看到此错误,例如-如果有人阻止您的IP继续进行连接。

相关问题