javascript - Jest + NodeJS 中的 super 测试,异步/等待

标签 javascript node.js async-await jestjs

我尝试用 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/

相关文章:

javascript - 如何检查指令中包含的表格的有效性?

javascript - 如何在纯 JavaScript 中实现 jQuery Mobile 动画 Ajax 页面导航(转换)

javascript - Promise 错误处理基础知识

c# - 在异步方法完成之前,UI 不会更新

c# - 在 Parallel.ForEach 中嵌套 await

javascript - 解析服务器中没有这样的文件或目录 - 云代码

javascript - React 和 websocket - 数据操作

jquery - "Typeahead is not a function"错误

node.js - WebStorm Node.Js 解释器问题

javascript - 在 async.each 回调之前等待 promise