I try to test my api with Jest. I want more abstraction, so i created this function:
const tokensConfig = config.get('test.tokens');
function testIt(method = 'get', url = '/', statuses = [], body = {}) {
const testNames = ['unauthorized', 'user', 'admin'];
const tokens = [null, tokensConfig.user, tokensConfig.admin];
for (let i = 0; i < testNames.length; i++) {
test(testNames[i], async () => {
const response = await request(app)
[method](url)
.set('Accept', 'application/json')
.set('Authorization', tokens[i])
.send(body);
expect(response.statusCode).toBe(statuses[i]);
});
}
}
In test.js file i run:
const config = require('config');
const request = require('supertest');
const testIt = require('./testIt');
const app = require('../app');
// It's work
describe('get user by email', () => {
testIt('get', '/users/get-by-email/user@test', [401, 403, 200]);
});
// It's not work
describe('delete user', async () => {
const userByEmail = await request(app)
.get('/users/get-by-email/user@test')
.set('Accept', 'application/json')
.set('Authorization', config.get('test.tokens.admin'));
testIt('delete', `/users/${userByEmail._id}`, [401, 403, 200]);
});
Trouble in async/await - testIt running before request user.
If i move test (or it) to describe block from function testIt and create request user inside test, it will work. But i want more abstraction (test block very big for many tests)
How fix it?
Looks like you need to let jest know that the expect is an async method, with resolves
.
Here is the sample code from Jest's documentation:
// async/await can be used.
it('works with async/await', async () => {
expect.assertions(1);
const data = await user.getUserName(4);
expect(data).toEqual('Mark');
});
// async/await can also be used with `.resolves`.
it('works with async/await and resolves', async () => {
expect.assertions(1);
await expect(user.getUserName(5)).resolves.toEqual('Paul');
});
https://facebook.github.io/jest/docs/en/tutorial-async.html#async-await
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With