使用Chai断言比较两个对象

时间:2019-12-12 15:50:50

标签: node.js mocha chai

我有两个混合订单数组

from openpyxl import load_workbook
writer = pd.ExcelWriter(filename, engine='openpyxl')

try:
    # try to open an existing workbook
    writer.book = load_workbook(filename)

    # get the last row in the existing Excel sheet
    # if it was not specified explicitly
    if startrow is None and sheet_name in writer.book.sheetnames:
        startrow = writer.book[sheet_name].max_row

    # truncate sheet
    if truncate_sheet and sheet_name in writer.book.sheetnames:
        # index of [sheet_name] sheet
        idx = writer.book.sheetnames.index(sheet_name)
        # remove [sheet_name]
        writer.book.remove(writer.book.worksheets[idx])
        # create an empty sheet [sheet_name] using old index
        writer.book.create_sheet(sheet_name, idx)

    # copy existing sheets
    writer.sheets = {ws.title: ws for ws in writer.book.worksheets}
except FileNotFoundError:
    # file does not exist yet, we will create it
    pass

if startrow is None:
    startrow = 0

# write out the new sheet
df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

# save the workbook
writer.save()

我已经编写了以下代码,以使用chai断言比较它们

var actualResult = [{
start: "30",
end: "50",
locations: ["loc1", "loc2"]
},
{
start: "20",
end: "40",
locations: ["loc3", "loc4"]
}]

var expectedResult = [
{
    start: "20",
    end: "40",
    locations: ["loc4", "loc3"]
},
{
    start: "30",
    end: "50",
    locations: ["loc2", "loc1"]
}
]

效果很好,但是我很想知道我是否可以在一行中执行任何直接的chai断言

describe("test1", function () {
it('expect test', function () {
    expect(actualResult).to.have.length(expectedResult.length)
    for (b of expectedResult) {
        var found = false;
        for (d of actualResult) {
            if ((b.start == d.start) && (b.end == d.end)) {
                expect(b.locations).to.have.deep.members(d.locations)
                found = true;
            }
        }
        expect(found).to.be.true
    }
})

或更好的建议。

1 个答案:

答案 0 :(得分:0)

您可以使用 deep-equal-in-any-order 插件。

<块引用>

Chai 插件,用于匹配对象和数组深度相等,数组(包括嵌套数组)以任意顺序排列。

<块引用>

它的工作方式与 deep.equal 类似,但它不检查数组的顺序(在嵌套对象和数组的任何级别)。数组元素可以是任何JS实体(布尔值、空值、数字、字符串、对象、数组……)。

例如

const deepEqualInAnyOrder = require('deep-equal-in-any-order');
const chai = require('chai');

chai.use(deepEqualInAnyOrder);

const { expect } = chai;

describe('', () => {
  it('should pass', () => {
    const actualResult = [
      {
        start: '30',
        end: '50',
        locations: ['loc1', 'loc2'],
      },
      {
        start: '20',
        end: '40',
        locations: ['loc3', 'loc4'],
      },
    ];

    const expectedResult = [
      {
        start: '20',
        end: '40',
        locations: ['loc4', 'loc3'],
      },
      {
        start: '30',
        end: '50',
        locations: ['loc2', 'loc1'],
      },
    ];

    expect(actualResult).to.deep.equalInAnyOrder(expectedResult);
  });
});

测试结果:

  59308311
    ✓ should pass


  1 passing (23ms)