Is this correct that I would have to modify all the code that uses arrow functions in order to test them?

41 Views Asked by At

My background with unit testing is minimal.

From what I've found on Google it appears that I would have to change a lot of the code in our application in order to unit test arrow function code.

So, if code were as follow

 class MyComponent {
   fun: () => 'hello';
   constructor() {};
 }

Then I must change it to something like the following in order to unit test it.

Create an interface

Interface MyService {
  fun: () => string;
}

And change the code,

class Component {
   constructor() {
     this.mysService = () => {
       return {
         fun: () => 'hello'
       };
     };
   }
   myService: () => MyService;
 }
1

There are 1 best solutions below

0
On

I don't think you need to change anything in your code in order to test your arrow functions:

Assuming you have this component with the myFunc arrow function:

export class TestcomponentComponent implements OnInit {

  constructor() { }
  myfunc = () => 'hello';

  ngOnInit(): void {
  }

}

in your spec file, you can do the following:

describe('TestcomponentComponent', () => {
  let component: TestcomponentComponent;
  let fixture: ComponentFixture<TestcomponentComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [TestcomponentComponent]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(TestcomponentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('myFunc should return "hello"', () => {
    expect(component.myfunc()).toBe('hello');
  })
});