santi
santi

Reputation: 582

How to unit test just one function, without browser, on Angular

Let's say I have a function that performs a very long calculation:

export const veryLongCalculation = () => 1 + 1;

How can I unit test this function in Angular without opening Karma and without configuring anything else?

I would like to write a test like this one:

describe('Difficult Calculations', () => {
  it('should calculate', () => {
    const calcul = veryLongCalculation();
    expect(calcul).toBe(2);
  });
})

If I run ng test it starts Karma and the browser (and takes ages).

Can I run just that test without opening a browser and initializing everything? I guess there should be a command to do it, already configured. How?

Upvotes: 1

Views: 1857

Answers (1)

Milan Tenk
Milan Tenk

Reputation: 2715

I suggest trying Chrome in headless mode. This way Karma and Chrome remain, but the browser window won't be opened and the process will be quicker.

To test it add a script to package.json:

"test-headless": "ng test --watch=false --browsers=ChromeHeadless"

And run it using npm run test-headless.

Note that an Angular-based code runs in a browser, so it is highly recommended to run the test suits in a browser. Otherwise, the tests could have false positive/negative results.

Upvotes: 3

Related Questions