簡體   English   中英

如何使用Mocha / Chai測試Mongoose CRUD操作?

[英]How to test Mongoose CRUD operations with Mocha/Chai?

我正在嘗試測試此功能,該功能通過數據庫進行所有未執行的貨幣交易的梳理,並檢查價格是否匹配。 如果找到一個,則會進行數據庫調用以關閉交易者余額的交易增量。 我通過另一個函數(一系列API調用)將價格傳遞給它。 這是有問題的功能:

 function executeTrade(pricesArr) {
  // currencies array must match up one-to-one with pricesArr array
  const currencies = ['btc', 'ltc', 'eth', 'doge'];
  let chosen;
  // Pull trades from database
  return Trade.find().then(dbTrades => {
    console.log('foo')
    // Get only open trades
    const openTrades = dbTrades.filter(trade => trade.open);
    openTrades.forEach(trade => {
      const balance = `${trade.curr_bought}_balance`;
      // Get price to compare
      if (trade.curr_bought === 'usd') chosen = pricesArr[0];
      else {
        for (let i = 0; i < currencies.length; i++) {
          if (trade.curr_bought === currencies[i]) {
            chosen = pricesArr[i];
          }
        }
      }
      // Do math depending on buying BTC with USD or something else
      if ((trade.curr_bought === 'usd' && trade.sold_amount >= (trade.bought_amount / chosen)) || (trade.sold_amount >= chosen * trade.bought_amount)) {
        // Close trade order
        return trade.update({$set: { "open": false }})
          .then(() => {

          // Update user's balance to reflect successful trade
          return User.findOne({"_id": trade.owner}).then(user => {
            user.update({
              $set: {
                [balance]: user[balance] + parseFloat(trade.bought_amount)
              }
            }).then(doc => {
              res.json(doc);
            }).catch(err => console.log(err));
          }).catch(err => console.log(err));
        });
      }
    });
  });
};

我正在嘗試使用以下測試代碼對其進行測試:

it('Executes a trade if the specified sell prices are greater than or equal to the reported VWAP', done => {
const pricesArr = [0.1, 1, 1, 1];
executeTrade(pricesArr);
app
  .get(`/api/trades/?_id=${testTrade._id}`)
  .set('Accept', 'application/json')
  .expect('Content-Type', /json/)
  .expect(200)
  .end((err, res) => {
    console.log(res.body);
    expect(res.body[0].open).to.be.false;
    done();
  });

}); 問題在於測試中沒有執行任何數據庫調用。 該功能以及所有其他測試在調用Express服務器時可以正常工作,而我正在使用Express服務器在實際的Web應用程序上進行這些調用。

我什至嘗試了在it()函數的上下文中以及在out中都執行一個簡單的find操作,但是沒有一個都被執行。

我在想什么?

因為您的executeTrade函數是異步執行的,所以不能保證它包含的異步調用將在下一個函數調用之前完成(即在測試中進行API調用)。 嘗試這樣的事情:

executeTrade(pricesArr)
  .then(() => {
    // make api call and check expected
  });

這樣可以確保executeTrade返回的承諾在運行“ then”塊的內容之前就已結算。 此外,您將在forEach構造內部返回promise,這再次意味着,不能保證在executeTrade函數返回之前將對promise的結果進行結算。 要解決此問題,我建議改用類似以下的模式:

return Promise.all(openTrades.map((trade) => {
  // do stuff here
});

只有在map函數中返回的所有promise都兌現或其中一個拒絕時,這種情況才會解決。

最后,看起來您的executeTrades函數可能會多次調用res.json()。 您不能多次響應同一請求,而且我也看不到函數中定義了res的位置,因此也可以避免這種情況。

Google對諾言有很好的指導 ,我建議您看看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM