Recently I was modifying some unit tests in Angular. The code was spying on a property and returning a value. Something like this:

view plain print about
1beforeEach(function() {
2 spyOnProperty(component, "myValue", "get").and.returnValue(1);
3});

We had three or four tests using this spy. However, I had changed the code and wanted to add a new test that used a different return value. I could not re-create the spy, because that gave me an error message that the spy was already created.

I could have moved the spy out of the beforeEach() block and put it into the each individual test, but that didn't seem like a good encapsulated approach.

I could have also used different describe() blocks with different beforeEach() blocks setting up the spy with different return values. For one additional test on an existing method, that seemed like overkill.

There is a different way. First, save a reference to the spy:

view plain print about
1let myValueSpy;
2beforeEach(function() {
3 myValueSpy = spyOnProperty(component, "myValue", "get").and.returnValue({
4 prop1: 'a',
5 prop2: 'b'
6 });
7});

Then in my test I can use the spy reference to change the return value:

view plain print about
1it('should do something when something', () => {
2 myValueSpy.and.returnValue({
3 prop1: 'x',
4 prop2: 'a'
5 });
6 // rest of the test
7)
8});

Tada! That's what I needed.