Complex model tests

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.

These POJOs are using the same structure as what we expect to be returned in JSON format from backend REST endpoints. Defining object tests like these can therefore easily extend into integration tests that will call an actual web service, and rehydrate our models from POJOs.

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.

Using simple tests like these can also help to test scenarios where some of the properties are not set. In other words, where complex models are being hydrated from a REST endpoint, there may be cases where some of the properties are simply omitted. This scenario is fairly common in REST endpoints where the returned JSON structure may change depending on the use case. Our tests can therefore cater for these variations, and ensure that all functionality works as expected, for a variety of combinations of properties.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.137.218