【问题标题】:AssertionError [ERR_ASSERTION]: Missing expected rejection (Error)AssertionError [ERR_ASSERTION]:缺少预期的拒绝(错误)
【发布时间】:2021-09-30 03:51:49
【问题描述】:

所以,我正在尝试使用 MochaJS、SinonJS、rewire、chai 和 assert 为我的代码编写一些单元测试。我收到以下错误:

 1) async function addOneRoom(db, newRoom)
   should reject error when the maximum room number has been reached:
 AssertionError [ERR_ASSERTION]: Missing expected rejection (Error).
  at async Context.<anonymous> (test\test.js:33:9).

所以我正在测试的功能如下:

async function addOneRoom(db, newRoom) {
const roomNumber = await createRoomNumber(db, newRoom.floor);

if (roomNumber !== 0) {
    newRoom.roomNumber = roomNumber;
    const result = await db.rooms.insertOne(newRoom);
    return newRoom
} else return new Error("No room can be added on this floor. The maximum numar of rooms has been reached")}

我的单元测试是:

describe("async function addOneRoom(db, newRoom)", () => {
const addOneRoom = rewired.__get__("addOneRoom")
const sandBox = sinon.createSandbox()

it("should reject error when the maximum room number has been reached", async () => {
    const newRoom = {
        floor: 1,
        sqm: 20,
        capacity: 5,
        features: {
            videoProjector: 1,
            stage: 2
        }
    }

    const insertOne = sandBox.stub().returns()
    const mockedCreateRoomNumber = sandBox.stub().resolves(0)

    const db = {
        rooms: { insertOne }
    }

    const stubbedRoomNumber = rewired.__set__({ createRoomNumber: mockedCreateRoomNumber })
    await assert.rejects(addOneRoom(db, newRoom), new Error("No room can be added on this floor. The maximum numar of rooms has been reached"))

    // sandBox.assert.calledOnceWithExactly(stubbedRoomNumber)
    sandBox.assert.calledOnceWithExactly(insertOne, {newRoom})

    const order = [
        // stubbedRoomNumber,
        insertOne
    ]

    sandBox.assert.callOrder(...order)
    stubbedRoomNumber()
})

我将不胜感激!

【问题讨论】:

    标签: javascript node.js mocha.js chai sinon


    【解决方案1】:

    不要返回错误,抛出它:

    throw new Error("No room can be added on this floor. The maximum numar of rooms has been reached")}
    

    返回错误与返回其他内容没有什么不同,并且不会导致 promise 被拒绝。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 2020-09-17
      • 2018-02-07
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多