Asynchronous 开玩笑不';Don’不要等到async完成
我正在尝试从RESTAPI获取所有用户Asynchronous 开玩笑不';Don’不要等到async完成,asynchronous,jestjs,e2e-testing,supertest,Asynchronous,Jestjs,E2e Testing,Supertest,我正在尝试从RESTAPI获取所有用户 describe('GET', () => { let userId; // Setup create the mock user beforeAll(async () => { //Create the user return await request .post(routes.users.create) .set('Accept', 'applica
describe('GET', () => {
let userId;
// Setup create the mock user
beforeAll(async () => {
//Create the user
return await request
.post(routes.users.create)
.set('Accept', 'application/json')
.send(TEST_USER_DATA)
.then(res => userId = res.body.id)
})
// Clean up, deleting all the fake data that we created for this test suite
afterAll(async () => {
// Clean up, delete the user we created
return await request.delete(routes.users.delete(userId));
})
it('should get all users', async () => {
const usersResponse = await request
.get(routes.users.getAll)
.set('Accept', 'application/json')
.expect(200)
.expect('Content-Type', /json/);
// Logs an empty array
console.log(usersResponse.body);
expect(usersResponse.status).to.equal(200);
expect(Array.isArray(usersResponse.body)).to.be.true();
});
});
但是它看起来好像我的it()
块没有等待beforeAll()
完成,因为userResponse.body()
只是一个空数组。但是当我在Postman中做同样的思考时(例如,创建一个模拟用户,然后获取所有用户,它会显示一个包含我们创建的用户的数组),所以问题肯定不在服务器端
我已经试过这样写我以前的作品:
beforeAll(async () => {
//Create the user
return await new Promise((resolve) => {
request
.post(routes.users.create)
.set('Accept', 'application/json')
.send(TEST_USER_DATA)
.then(res => userId = res.body.id)
.then(() => resolve)
})
})
beforeAll(async (done) => {
//Create the user
request
.post(routes.users.create)
.set('Accept', 'application/json')
.send(TEST_USER_DATA)
.then(res => userId = res.body.id)
.then(() => done());
})
就像这样:
beforeAll(async () => {
//Create the user
return await new Promise((resolve) => {
request
.post(routes.users.create)
.set('Accept', 'application/json')
.send(TEST_USER_DATA)
.then(res => userId = res.body.id)
.then(() => resolve)
})
})
beforeAll(async (done) => {
//Create the user
request
.post(routes.users.create)
.set('Accept', 'application/json')
.send(TEST_USER_DATA)
.then(res => userId = res.body.id)
.then(() => done());
})
但他们两人都没有成功
编辑
正如@jornsharpe建议的那样,我在之前稍微更改了一下我的,
,以检查响应状态,我们实际上创建了一个用户
beforeAll(async () => {
//Create the user
return await request
.post(routes.users.create)
.set('Accept', 'application/json')
.send(TEST_USER_DATA)
.expect(200)
.then(res => {
userId = res.body.id;
// Log the correct user
console.log(res.body);
})
})
而且
beforeAll
块不会失败,因此创建用户本身工作正常。创建用户的请求是否一定成功?如果您添加例如.expect(201)
或注销响应,这会告诉您什么吗?如果在测试中移动创建,它是否有效?是否有效?创建资源的帖子应该成功201 Created
。如果你例如.expect(404)
,它会失败吗?@jornsharpe是的,它100%有效,我在《邮差》上测试过。关于返回代码,出于某种原因,此项目的要求是POST请求返回200而不是201。您是否解决过此问题?是否可能是服务器速度太慢,导致beforeAll中的POST请求达到超时(默认值:5s)并且测试开始得太早?@OlgaKedel我遇到了类似的问题,在调用Beforeach(在同一文件中)之前,asyncBeforeach
无法完成。以前Jest的似乎确实存在问题,因为相同的代码在Jest之外也可以正常工作。