open-nomad/ui/tests/unit/serializers/application-test.js
Buck Doyle 4394c5b9ff
Add common serialiser abstractions (#8634)
This extracts some common API-idiosyncracy-handling patterns from model serialisers into properties that are processed by the application serialiser:

* arrayNullOverrides converts a null property value to an empty array
* mapToArray converts a map to an array of maps, using the original map keys as Name properties on the array maps
* separateNanos splits nanosecond-containing timestamps into millisecond timestamps and separate nanosecond properties
2020-08-20 12:14:49 -05:00

108 lines
2.6 KiB
JavaScript

import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import ApplicationSerializer from 'nomad-ui/serializers/application';
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
class TestSerializer extends ApplicationSerializer {
arrayNullOverrides = ['Things'];
mapToArray = [
'ArrayableMap',
{ beforeName: 'OriginalNameArrayableMap', afterName: 'RenamedArrayableMap' },
];
separateNanos = ['Time'];
}
class TestModel extends Model {
@attr() things;
@attr() arrayableMap;
@attr() renamedArrayableMap;
@attr() time;
@attr() timeNanos;
}
module('Unit | Serializer | Application', function(hooks) {
setupTest(hooks);
hooks.beforeEach(function() {
this.store = this.owner.lookup('service:store');
this.owner.register('model:test', TestModel);
this.owner.register('serializer:test', TestSerializer);
this.subject = () => this.store.serializerFor('test');
});
const normalizationTestCases = [
{
name: 'Null array and maps',
in: {
ID: 'test-test',
Things: null,
ArrayableMap: null,
OriginalNameArrayableMap: null,
Time: 1607839992000100000,
},
out: {
data: {
id: 'test-test',
attributes: {
things: [],
arrayableMap: [],
renamedArrayableMap: [],
time: 1607839992000,
timeNanos: 100096,
},
relationships: {},
type: 'test',
},
},
},
{
name: 'Non-null array and maps',
in: {
ID: 'test-test',
Things: [1, 2, 3],
ArrayableMap: {
a: { Order: 1 },
b: { Order: 2 },
'c.d': { Order: 3 },
},
OriginalNameArrayableMap: {
a: { X: 1 },
},
Time: 1607839992000100000,
SomethingExtra: 'xyz',
},
out: {
data: {
id: 'test-test',
attributes: {
things: [1, 2, 3],
arrayableMap: [
{ Name: 'a', Order: 1 },
{ Name: 'b', Order: 2 },
{ Name: 'c.d', Order: 3 },
],
renamedArrayableMap: [{ Name: 'a', X: 1 }],
time: 1607839992000,
timeNanos: 100096,
},
relationships: {},
type: 'test',
},
},
},
];
normalizationTestCases.forEach(testCase => {
test(`normalization: ${testCase.name}`, async function(assert) {
assert.deepEqual(this.subject().normalize(TestModel, testCase.in), testCase.out);
});
});
});