1

So I have a function with a sort that I am trying to unit test with Jasmine.

loadData() {
    this.Service.getAll().subscribe(res => {
        res.sort((x) => {
            return x.Name, x.Id
        });
        this.stuff = res;
    });
}

From what I have found, because the sort is an array.Prototype, I need to add a spyon the method. I have tried both of the following, but they don't handle it:

spyOn(Array.prototype,'sort').and.callThrough();
spyOn(Array.prototype,'sort');

I'm new to Jasmine, So I assume I am just missing something obvious. How do I handle this?

Thanks

Limey
  • 2,642
  • 6
  • 37
  • 62

1 Answers1

2

It's a bad idea to spy on a prototype, you should spy on an instance instead. Take a look at this post. Actually, you are trying to test the method implementation, but you should test the class API instead. When you use a class, you don't think about its implementation, usually you even don't know how the class is implemented, it's just a black box. You should test the class the same way, otherwise it will be hard to maintain such tests, you'll have to update tests each time the implementation is changed. The loadData() method changes the object state somehow, just check that the state is changed correctly.

Valeriy Katkov
  • 33,616
  • 20
  • 100
  • 123