javascript - 使用 jest 和 supertest 使用 async/await 在 Javascript 中测试数据库插入

标签 javascript testing async-await jestjs supertest

我正在尝试为 React/Postgres 堆栈编写测试,你猜怎么着?它有效……有时 :-(

我正在使用帮助文件在测试之间重置数据库:

// partial contents of dbtools.js
function clean_db(){
  const client = new Client(dbConfig);
  client.connect();
  client.query( 
    `TRUNCATE TABLE "templates"; 
     ALTER SEQUENCE "templates_id_seq" RESTART WITH 1;`
    )
    .catch( err => { console.error(err); } )
    .then( () => client.end() );
}

测试本身大致是:

const request = require('supertest');
const app = require('../app');
const { Client } = require('pg');
const SQL = require('sql-template-strings');
const dbConfig = require('../db');
const { clean_db } = require('./helpers/dbtool');
const faker = require('faker');

async function insertTemplate(myTemplate) {
  const client = new Client(dbConfig);
  const { name, status, version } = myTemplate;
  client.connect();
  await client.query(
    SQL`INSERT INTO templates (name, status, version )
    VALUES (${name}, ${status}, ${version})
    RETURNING id`)
    .catch( err => console.error(err) )
    .then( () => client.end() );
}

function randomTemplate() {
  return {
    name: faker.internet.userName,
    status: 'new',
    version: String(faker.random.number())
  };
}


beforeAll(async () => {
  await clean_db();
});

afterAll(async () => {
  await clean_db();
});

describe('GET /templates', () => {

  //... other tests ...

  describe('When there are 1 or more records in the table', () => {

    const templ1 = randomTemplate();
    const templ2 = randomTemplate();
    const templ3 = randomTemplate();

    beforeEach(async () => {
      await clean_db();
      const t1_added = await insertTemplate(templ1);
      const t2_added = await insertTemplate(templ2);
      const t3_added = await insertTemplate(templ3);
    });

    afterEach(async () => {
      await clean_db();
    });

    // here's one example problem child
    test('It should respond with an JSON array of records', async done => {
      const response = await request(app).get('/templates');
      expect(response.body.length).toBe(3);
      console.error(response.body);
      done();
    });

    //... more tests ...

    });
  });
});

我怀疑插入没有在测试运行之前完成。

我得到的错误是:

 FAIL  tests/templates.test.js
  ● GET /templates › When there are 1 or more records in the table › It should respond with an JSON a
rray of records

    expect(received).toBe(expected) // Object.is equality

    Expected: 3
    Received: 2

      94 |     test('It should respond with an JSON array of records', async done => {
      95 |       const response = await request(app).get('/templates');
    > 96 |       expect(response.body.length).toBe(3);
         |                                    ^
      97 |       console.error(response.body);
      98 |       done();
      99 |     });

      at Object.toBe (tests/templates.test.js:96:36)

我在 async/await 方面做错了什么吗?策略是错误的吗?

最佳答案

我看到我们混合使用 async/await 和 promise,这并非没有必要。这可能是错误的罪魁祸首。

helper 可以改进为

async function clean_db() {
  const client = new Client(dbConfig);

  try { // using try catch to catch error
    await client.connect(); // specify await, take a look at its doc 

    await client.query( 
      `TRUNCATE TABLE "templates"; 
       ALTER SEQUENCE "templates_id_seq" RESTART WITH 1;`
      )

     await client.end(); // specify await
  } catch (err) {
    console.error(err);
  };
}

请注意,不再有 promise (then),我们只使用 async/await

insertTemplate 可以改进为

async function insertTemplate(myTemplate) {
  const client = new Client(dbConfig);
  const { name, status, version } = myTemplate;

  try {
    await client.connect();

    await client.query(
      SQL`INSERT INTO templates (name, status, version )
      VALUES (${name}, ${status}, ${version})
      RETURNING id`)

      await client.end();
  } catch (err) {
    console.error(err)
  }
}

引用: https://node-postgres.com/

关于javascript - 使用 jest 和 supertest 使用 async/await 在 Javascript 中测试数据库插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58539975/

相关文章:

JavaScript 数组映射

javascript - 为 JS 中的函数添加属性

iOS App Alpha 和 Beta 测试,超过 100 名测试人员

c# - 这是编写异步方法的正确方法吗?

javascript - 类变量在 JavaScript 中返回 undefined

javascript - setTimeout() 是否在单独的线程上运行?

ruby - 单元测试 ruby​​ 命令行应用程序的代码 - 如何模拟/传递 ARGV

regex - 创建 React App 找不到测试

microsoft-metro - 调试器无法识别等待方法返回值的变量

c# - 对 WCF 客户端的异步调用会阻止后续的同步调用