We can use the same techniques to test that complex models are instantiated correctly. Consider the following test suite:
describe("model.spec.ts : ItemCollectionViewModel tests", () => { let itemCollectionViewModel: ItemCollectionViewModel; beforeEach(() => { itemCollectionViewModel = new ItemCollectionViewModel({ Title: "testTitle", SelectedItem: { Id: 10, DisplayName: "testDisplayName" }, Name: "testName" }); });
Here, we are creating an instance of our complex model, named itemCollectionViewModel. The interesting bit is the construction of this complex model with a POJO. We are calling the constructor in our beforeEach function, and simply nesting POJOs within each other. We are setting the Title property, and then setting the SelectedItem property to another POJO that has the Id and DisplayName properties. Finally, we set the Name property.
Our unit tests for this complex model can then simply traverse the available properties to ensure that everything is set correctly, as follows:
it("should set the Title property", () => { expect(itemCollectionViewModel.Title).toBe("testTitle"); }); it("should set the SelectedItem.Id property", () => { expect(itemCollectionViewModel.SelectedItem.Id).toBe(10); }); it("should set the SelectedItem.DisplayName property", () => { expect(itemCollectionViewModel.SelectedItem.DisplayName) .toBe("testDisplayName"); }); it("should set the Name property", () => { expect(itemCollectionViewModel.Name).toBe("testName"); });
Our first test checks the value of the Title property, and then the following tests check the value of the SelectedItem property (which is a child Backbone model), and the Name property.