import{moduleForModel,test}from'ember-qunit';moduleForModel('cat','Unit | Serializer | cat',{// Specify the other units that are required for this test.needs:['serializer:cat']});// Replace this with your real tests.test('it serializes records',function(assert){varrecord=this.subject();varserializedRecord=record.serialize();assert.ok(serializedRecord);});

But how do you go about testing methods like normalizeResponse, keyForRelationship, or any of the other serializer methods? In the generated code above, neither record nor serializedRecord are instances of the serializer. Even if they were, I typically don’t interact with serializers directly. I use serializers indirectly through the data store. Because of that, I have found it most useful to write my unit tests for serializers by using the store.

Testing normalizeResponse()

Because I am using the RESTSerializer, I want to make sure the serializer transforms this JSON payload into the proper format that it expects. If you are using the RESTSerializer, your JSON payload is expected to be in the format:

I am using Pretender to fake out requests made to /cats and specified a static response in the same format that I expect the backend to return. Next, in my test I can access an instance of the data store (DS.Store) by calling this.store(). In order for this to be an asynchronous test, you return a promise from the test. This is noted on the ember-qunitdocumentation:

If you return a promise from a test callback it becomes an asyncTest. This is a key difference between ember-qunit and standard QUnit.

Inside the success callback, I write my assertions. Here I am simply checking that the length of the RecordArray is 3 which corresponds to the number of cats returned from the API.

This time, each cat returned from /cats has a foreign key home_id that points to the home the cat belongs to. By default, the RESTSerializer does not relate models using the XXX_id convention. Instead, it uses the relationship key name as the default. So if I wanted my JSON to fit what Ember Data expects, it would need to look like this:

In the needs array, I need to specify the related home model. Because my relationship is synchronous, I need to put the corresponding home into the store. Now when I retrieve all cats, I take the first one from the result and check if the related home model is correct by simply checking the address property.

Conclusion

Here is the full source code for the examples used in this post and all the passing tests.

Personally I have found testing serializers through the store to be the most straightforward since I never directly interact with serializers. If you test serializers differently, let me know your approach in the comments!