Jest 如何测试快速 API POST 请求?

use*_*502 5 node.js express jestjs

我需要使用 Jest 测试测试我对端点的 POST 请求是否正常工作。我的想法是首先获取我的服务表的计数(我正在使用 sequelize orm),然后发送一个新的 post 请求并最终获取新的计数并比较旧计数 + 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}`));
});
Run Code Online (Sandbox Code Playgroud)

});

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

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
Run Code Online (Sandbox Code Playgroud)

是否缺少某些内容,或者是否有更好的方法来测试 POST 请求?玩笑?

Sup*_*acy 9

这是因为您没有调用在 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()
            });
    });
});
Run Code Online (Sandbox Code Playgroud)

你也可以这样写这段代码,这样可以提高可读性,最大限度地利用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()
    }
});
Run Code Online (Sandbox Code Playgroud)

默认情况下,Jest 也会在 async/await case 中解析 promise。我们也可以在没有回调函数的情况下实现这一点

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}`)
    }
});
Run Code Online (Sandbox Code Playgroud)