2021-05-28 21:14:09 +03:00
|
|
|
import clone, { cloneInstance } from '@/utils/clone'
|
2020-10-26 00:07:23 +03:00
|
|
|
|
|
|
|
describe('clone', () => {
|
2021-05-28 21:14:09 +03:00
|
|
|
test('Basic objects stay the same', () => {
|
2020-10-26 00:07:23 +03:00
|
|
|
const obj = { a: 123, b: 'hello' }
|
|
|
|
expect(clone(obj)).toEqual(obj)
|
|
|
|
})
|
|
|
|
|
2021-05-28 21:14:09 +03:00
|
|
|
test('Basic nested objects stay the same', () => {
|
2020-10-26 00:07:23 +03:00
|
|
|
const obj = { a: 123, b: { c: 'hello-world' } }
|
|
|
|
expect(clone(obj)).toEqual(obj)
|
|
|
|
})
|
|
|
|
|
2021-05-28 21:14:09 +03:00
|
|
|
test('Simple pojo reference types are re-created', () => {
|
2020-10-26 00:07:23 +03:00
|
|
|
const c = { c: 'hello-world' }
|
|
|
|
expect(clone({ a: 123, b: c }).b === c).toBe(false)
|
|
|
|
})
|
|
|
|
|
2021-05-28 21:14:09 +03:00
|
|
|
test('Retains array structures inside of a pojo', () => {
|
|
|
|
const obj = { a: 'abc', d: ['first', 'second'] }
|
2020-10-26 00:07:23 +03:00
|
|
|
expect(Array.isArray(clone(obj).d)).toBe(true)
|
|
|
|
})
|
|
|
|
|
2021-05-28 21:14:09 +03:00
|
|
|
test('Removes references inside array structures', () => {
|
|
|
|
const obj = { a: 'abc', d: ['first', { foo: 'bar' }] }
|
2020-10-26 00:07:23 +03:00
|
|
|
expect(clone(obj).d[1] === obj.d[1]).toBe(false)
|
|
|
|
})
|
|
|
|
})
|
2021-05-28 21:14:09 +03:00
|
|
|
|
|
|
|
describe('cloneInstance', () => {
|
|
|
|
test('creates a copy of a class instance', () => {
|
|
|
|
class Sample {
|
|
|
|
constructor() {
|
|
|
|
this.fieldA = 'fieldA'
|
|
|
|
this.fieldB = 'fieldB'
|
|
|
|
}
|
|
|
|
|
|
|
|
doSomething () {}
|
|
|
|
}
|
|
|
|
|
|
|
|
const sample = new Sample()
|
|
|
|
const copy = cloneInstance(sample)
|
|
|
|
|
|
|
|
expect(sample === copy).toBeFalsy()
|
|
|
|
|
|
|
|
expect(copy).toBeInstanceOf(Sample)
|
|
|
|
expect(copy.fieldA).toEqual('fieldA')
|
|
|
|
expect(copy.fieldB).toEqual('fieldB')
|
|
|
|
expect(copy.doSomething).toBeTruthy()
|
|
|
|
expect(copy.doSomething).not.toThrow()
|
|
|
|
})
|
|
|
|
|
|
|
|
test('creates a broken copy of builtins', () => {
|
|
|
|
const sample = new Date()
|
|
|
|
const copy = cloneInstance(sample)
|
|
|
|
|
|
|
|
expect(sample === copy).toBeFalsy()
|
|
|
|
expect(copy).toBeInstanceOf(Date)
|
|
|
|
expect(() => copy.toISOString()).toThrow()
|
|
|
|
})
|
|
|
|
})
|