开玩笑如何测试Express API POST请求?

时间:2019-01-22 19:35:12

标签: node.js express jestjs

我需要通过Jest测试来测试对端点的POST请求是否正常工作。我的想法是先获取我的Services表的计数(我正在使用sequelize orm),然后发送新的发帖请求并最终获取新的计数,并比较旧计数+ 1是否等于新计数,如果为true,那么POST请求就可以正常工作。

test('Create a valid Service', async (done) => {
const service = {
    name: "cool",
    description: "description"
};

await Service.count().then(async function (count) {

    await request(app)
        .post('/api/services')
        .send(service)
        .then(async () => {
            await Service.count().then(function (newcount) {
                expect(newcount).toBe(count + 1);
            });
        })
        .catch(err => console.log(`Error ${err}`));
});

});

对我来说,测试看起来不错,但是当我运行它时,我得到了:

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.

是否缺少某些东西,或者还有更好的方法来测试POST请求?和开玩笑吗?

1 个答案:

答案 0 :(得分:2)

这是因为您没有调用jest回调函数中传递的 done 回调。可以这样做。

test('Create a valid Service', async(done) => {
    const service = {
        name: "cool",
        description: "description"
    };

    await Service.count().then(async function (count) {

        await request(app)
            .post('/api/services')
            .send(service)
            .then(async() => {
                await Service.count().then(function (newcount) {
                    expect(newcount).toBe(count + 1);
                    // execute done callback here
                    done();
                });
            })
            .catch(err => {
                // write test for failure here
                console.log(`Error ${err}`)
                done()
            });
    });
});

您还可以通过这种方式编写此代码,以提高可读性并最大限度地使用 async / await

test('Create a valid Service', async(done) => {
    const service = {
        name: "cool",
        description: "description"
    };
    try {
        const count = await Service.count();
        await request(app).post('/api/services').send(service)
        const newCount = await Service.count()
        expect(newCount).toBe(count + 1);
        done()
    } catch (err) {
        // write test for failure here
        console.log(`Error ${err}`)
        done()
    }
});

默认情况下, Jest还会在异步/等待情况下解决承诺。我们也可以不用回调函数来实现这一点

test('Create a valid Service', async() => {
    const service = {
        name: "cool",
        description: "description"
    };
    try {
        const count = await Service.count();
        await request(app).post('/api/services').send(service)
        const newCount = await Service.count()
        expect(newCount).toBe(count + 1);
    } catch (err) {
        // write test for failure here
        console.log(`Error ${err}`)
    }
});