Olg*_*del 6 asynchronous supertest jestjs e2e-testing
我正在尝试测试从我的 REST API 获取所有用户。
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();
});
});
Run Code Online (Sandbox Code Playgroud)
但看起来好像我的it()块没有等待beforeAll()完成,因为userResponse.body()它只是一个空数组。但是当我在 Postman 中做同样的思考时(例如创建一个模拟用户,然后获取所有用户,它会显示一个包含我们创建的用户的数组),所以问题绝对不在服务器端。
我已经尝试过这样编写 beforeAll 块:
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)
})
})
Run Code Online (Sandbox Code Playgroud)
像这样:
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());
})
Run Code Online (Sandbox Code Playgroud)
但他们都不起作用。
编辑
正如 @jonrsharpe 建议的那样,我做了beforeAll一些更改来检查响应状态,并且我们实际上创建了一个用户
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);
})
})
Run Code Online (Sandbox Code Playgroud)
并且该beforeAll块不会失败,因此用户的创建本身工作正常。
| 归档时间: |
|
| 查看次数: |
2850 次 |
| 最近记录: |