【问题标题】:Jest testing with Node - Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout使用 Node 进行 Jest 测试 - 超时 - 在 jest.setTimeout 指定的 5000 毫秒超时内未调用异步回调
【发布时间】:2019-04-23 04:10:52
【问题描述】:

我开始使用 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 指定的 5000 毫秒超时内未调用异步回调。'

问题:我怎样才能使这个测试通过?

【问题讨论】:

    标签: javascript node.js reactjs jestjs


    【解决方案1】:

    您可以使用resolves 获得异步结果,如shown in the Jest documentation

    在你的情况下:

    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
            })
        }
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        此外,如果您只是想增加超时时间,那么您可以通过设置来做到这一点

         jest.setTimeout(10000);

        如果您想更改该描述块中所有测试的超时时间,可以在 beforeEach 中使用此语句,如果您希望单个测试使用它,则可以在 test/it/spec 块中使用此语句。

        【讨论】:

          猜你喜欢
          • 2019-03-11
          • 2018-09-18
          • 2018-09-11
          • 2021-05-13
          • 2018-12-05
          • 2020-05-13
          • 2018-12-28
          • 2020-09-05
          相关资源
          最近更新 更多