Refs

Why unit tests?

CLI

// cd to app folder
ng test // test whole app
// Test only one file (jest.config.j s)
testMatch: ['**/web-integration-form.component.spec.ts'],

Understanding concepts

Is app properly created?

👉🏻 Difference: fixture.debugElement.componentInstance & fixture.componentInstance

// First and nothing
it('should create the app', () => {
  let fixture = TestBed.createComponent(UserComponent); // create a store new component in "fixture"
  let app = fixture.debugElement.componentInstance; // need "debugElement" if without browsers
  expect(app).toBeTruthy();
	
	// example of inspect a property "title" of component
	// (what comes in  the class)
	expect(app.title)...
});

TestBed

👉 Angular - TestBed

Different providers

Mocking

Mock a “read only” property of a class (”get”)

⚠️ This is my personal note, it may be not a perfect (or “right”) way!

// LexiconSessionService
// 👇 We want to mock this one!
export class LexiconSessionService {
	get lexiconStatusObj(): SomeType {
	  return {
	    // something
	  };
	}
}
beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [LexiconComponent], // wanna test
    providers: [
			// Despite we use `useValue` here
      { provide: LexiconSessionService, useValue: mockLexiconSessionService },
    ]
  }).compileComponents();
});

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

describe('Test something', () => {
	it('should do something', () => {
		const _lexicon = TestBed.inject(LexiconSessionService);
		// 🤩 Key point!!!
		Object.defineProperty(_lexicon, 'lexiconStatusObj', {
      value: fakeLexiconStatusObj, // fake return value!!!
      writable: true
    });
		// other tests which call _lexicon.lexiconStatusObj
	});
});

Test a component