我尝试用 Jest 测试我的 api。我想要更多的抽象,所以我创建了这个函数:
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]);
});
}
}
在我运行的 test.js 文件中:
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]);
});
async/await 中的问题 - testIt 在请求用户之前运行。
如果我移动测试(或它)来描述函数 testIt 中的 block 并在测试中创建请求用户,它将起作用。但我想要更多的抽象(测试 block 对于许多测试来说非常大)
如何解决?
最佳答案
看起来你需要让 jest 知道 expect 是一个异步方法,带有 resolves
。
以下是 Jest 文档中的示例代码:
// 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
关于javascript - Jest + NodeJS 中的 super 测试,异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50134457/