Javascript 与DB和Chai异步

Javascript 与DB和Chai异步,javascript,node.js,asynchronous,rethinkdb,chai,Javascript,Node.js,Asynchronous,Rethinkdb,Chai,试着把我的脑袋绕在这上面,这让我的思维陷入了一个异步循环 在运行这个简单的测试之后,当我手动检查数据库时,结果是正确的(在数据库“test”中有一个名为“books”的表);但是,无论我在chai的expect函数中断言什么,这个测试都通过了。我知道这是一个异步问题,因为测试完成后,console.log(result)会打印到控制台。我本以为在Rejection获得tableList()后,expect会运行,因为它在回调中 为什么这个测试通过了(如果['books']===['anythin

试着把我的脑袋绕在这上面,这让我的思维陷入了一个异步循环

在运行这个简单的测试之后,当我手动检查数据库时,结果是正确的(在数据库“test”中有一个名为“books”的表);但是,无论我在chai的
expect
函数中断言什么,这个测试都通过了。我知道这是一个异步问题,因为测试完成后,
console.log(result)
会打印到控制台。我本以为在Rejection获得
tableList()
后,
expect
会运行,因为它在回调中

  • 为什么这个测试通过了(如果
    ['books']===['anything']
    ,它应该会失败)
  • 为什么
    expect()
    不在
    tableList()之后运行
  • 将命令链接到数据库以便按顺序执行的正确方法是什么
  • db_spec.js:

    import {expect} from 'chai'
    import r from 'rethinkdb'
    
    describe('rethinkdb', () => {
      it('makes a connection', () => {
        var connection = null;
        r.connect({host: 'localhost', port: 28015}, function(err, conn) {
          if (err) throw err
          connection = conn
    
          r.dbDrop('test').run(connection, () => {
            r.dbCreate('test').run(connection, () => {
              r.db('test').tableCreate('books').run(connection, () => {
                r.db('test').tableList().run(connection, (err, result) => {
                  if (err) throw err
                  console.log(result)
                  expect(result).to.equal(['anything'])
                })
              })
            })
          })
        })
      })
    })
    

    我认为这会起作用,但是最内部的回调没有被执行,测试只是超时

    import {expect} from 'chai'
    import r from 'rethinkdb'
    
    describe('rethinkdb', () => {
      it('makes a connection', (done) => {
        var connection = null;
        r.connect({host: 'localhost', port: 28015}, function(err, conn) {
          if (err) throw err
          connection = conn
    
          r.dbDrop('test').run(connection, () => {
            r.dbCreate('test').run(connection, () => {
              r.db('test').tableCreate('books').run(connection, () => {
                r.db('test').tableList().run(connection, (err, result) => {
                  if (err) throw err
                  expect(result[0]).to.equal('books').done()
                })
              })
            })
          })
        })
      })
    })
    

    我认为您应该使用
    expect(result).to.deep.equal(…)
    。在Javascript中直接比较数组并不是那么简单。至于异步问题,您的测试用例没有进行
    done
    回调,因此框架假设您的测试是同步的。要解决这个问题,测试用例声明应该是
    it('make a connection',(done)=>…)
    ,您应该在您的
    expect
    之后调用
    done()
    @Tryneus谢谢。查看修改后的代码。仍然存在一些问题。@Tryneus实际上,不管怎样,出于某种原因,它仍然没有读取最内部的回调。非常有用的链接帮助我理解: