gpt4 book ai didi

javascript - 我应该如何测试两个嵌套的不可变 js 数据结构的深度相等性?

转载 作者:行者123 更新时间:2023-11-29 16:41:55 26 4
gpt4 key购买 nike

假设我有以下嵌套的不可变数据结构:

import { Record, List } from 'immutable'

const foo = List([
Record({
id: 1,
gameState: Record({})
})
])

我如何测试两个嵌套的不可变 js 数据结构彼此相等?

test.js

import jest from 'jest'
import { Record, List } from 'immutable'

describe('test', () => {
it('that foo equals expected', () => {
const expected = List([
Record({
id: 1,
gameState: Record({})
})
])
expect(foo).toEqual(expected)
})

最佳答案

对于大多数 ImmutableJS 类型,您进行的测试都可以正常工作。问题在于您使用记录的方式。与 Map、List 等不同,constructorRecord(...) 不返回新对象,它返回一个构造函数,然后可以使用该构造函数创建新对象。来自文档(https://facebook.github.io/immutable-js/docs/#/Record):

[Record] Creates a new Class which produces Record instances. A record is similar to a JS object, but enforce a specific set of allowed string keys, and have default values.

如果你想记录用户,那么你可以这样写你的测试:

import { Record, List, is } from 'immutable'

describe('test', () => {
it('that foo equals expected', () => {
const gameState = Record({});
const gameRecord = Record({
id: 1,
gameState: new gameState()
});

const foo = List([
new gameRecord()
]);

const expected = List([
new gameRecord()
]);
expect(foo.equals(expected)).toBe(true);
})
});

将此与使用 map 而不是记录进行比较。下面使用 jest 的 toEqual 函数的测试按预期通过:

import { Map, List, is } from 'immutable'

describe('test', () => {
it('that foo equals expected', () => {

const foo = List([
Map({
id: 1,
gameState: Map({})
})
]);

const expected = List([
Map({
id: 1,
gameState: Map({})
})
])
expect(foo).toEqual(expected);
})
});

关于javascript - 我应该如何测试两个嵌套的不可变 js 数据结构的深度相等性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44863719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com