簡體   English   中英

JEST和MongoDB的異步問題

[英]Asynchronous Issues with JEST and MongoDB

當我嘗試使用beforeEach()掛鈎從MongoDB集合中刪除項目時,JEST的結果不一致。

我的貓鼬模式和模型定義為:

// Define Mongoose wafer sort schema
const waferSchema = new mongoose.Schema({
  productType: {
    type: String,
    required: true,
    enum: ['A', 'B'],
  },
  updated: {
    type: Date,
    default: Date.now,
    index: true,
  },
  waferId: {
    type: String,
    required: true,
    trim: true,
    minlength: 7,
  },
  sublotId: {
    type: String,
    required: true,
    trim: true,
    minlength: 7,
  },
}

// Define unique key for the schema
const Wafer = mongoose.model('Wafer', waferSchema);
module.exports.Wafer = Wafer;

我的JEST測試:

describe('API: /WT', () => {
  // Happy Path for Posting Object
  let wtEntry = {};

  beforeEach(async () => {
    wtEntry = {
      productType: 'A',
      waferId: 'A01A001.3',
      sublotId: 'A01A001.1',
    };
    await Wafer.deleteMany({});
    // I also tried to pass in done and then call done() after the delete
  });

  describe('GET /:id', () => {
    it('Return Wafer Sort Entry with specified ID', async () => {
      // Create a new wafer Entry and Save it to the DB
      const wafer = new Wafer(wtEntry);
      await wafer.save();

      const res = await request(apiServer).get(`/WT/${wafer.id}`);
      expect(res.status).toBe(200);
      expect(res.body).toHaveProperty('productType', 'A');
      expect(res.body).toHaveProperty('waferId', 'A01A001.3');
      expect(res.body).toHaveProperty('sublotId', 'A01A001.1');
    });
}

因此,當我多次運行測試時,我總是得到的錯誤與重復鍵有關:MongoError:E11000重復鍵錯誤集合:promis_tests.promiswts索引:WaferId_1_sublotId_1 dup鍵:{:“ A01A001.3”,:“ A01A001.1 “}

但是我不明白,如果beforeEach()正確觸發,如何得到這個重復的鍵錯誤。 我是否試圖不正確地清除收藏夾? 我試過在每個回調之前將完成的元素傳遞給before,並在delete命令之后調用它。 我也嘗試過在beforeAll(),afterEach()和afterAll()中實現刪除,但結果仍然不一致。 我對此很困惑。 我可能只是一起刪除了架構鍵,但我想了解beforeEach()在這里發生了什么。 在此先感謝您的任何建議。

如果不刪除架構索引,這似乎是最可靠的解決方案。 不100%知道為什么它可以通過異步等待Wafer.deleteMany({});

beforeEach((done) => {
    wtEntry = {
      productType: 'A',
      waferId: 'A01A001.3',
      sublotId: 'A01A001.1',
    };
    mongoose.connection.collections.promiswts.drop(() => {
      // Run the next test!
      done();
    });
});

可能是因為您實際上並未使用貓鼬必須提供的promise API。 默認情況下,像deleteMany()這樣的貓鼬函數不會返回promise。 您將必須在函數鏈的末尾調用.exec()才能返回承諾, eg await collection.deleteMany({}).exec() 因此,您遇到了競爭狀況。 deleteMany()也接受回調,因此您始終可以將其包裝在promise中。 我會做這樣的事情:

 describe('API: /WT', () => { // Happy Path for Posting Object const wtEntry = { productType: 'A', waferId: 'A01A001.3', sublotId: 'A01A001.1', }; beforeEach(async () => { await Wafer.deleteMany({}).exec(); }); describe('GET /:id', () => { it('Return Wafer Sort Entry with specified ID', async () => { expect.assertions(4); // Create a new wafer Entry and Save it to the DB const wafer = await Wafer.create(wtEntry); const res = await request(apiServer).get(`/WT/${wafer.id}`); expect(res.status).toBe(200); expect(res.body).toHaveProperty('productType', 'A'); expect(res.body).toHaveProperty('waferId', 'A01A001.3'); expect(res.body).toHaveProperty('sublotId', 'A01A001.1'); }); } 

另外,請始終期望使用異步代碼https://jestjs.io/docs/en/asynchronous.html的斷言

您可以在這里閱讀有關貓鼬承諾和查詢對象的更多信息https://mongoosejs.com/docs/promises.html

暫無
暫無

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

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