How to generate mock data for your Angular unit tests (Angular ➕ Faker)


Often when writing Angular tests we have to mock dependencies.

At least when writing unit tests. Or when you want to test Angular services that depend on the HTTP client.

But today we're going to learn how to generate fake data with a few lines of code. This fake data can serve all kinds of purposes.

We're going to be using a JavaScript library called Faker.

Faker is a library that generates fake (but reasonable) data and is a great way to generate data for unit tests.

You can use it to generate huge amounts data for testing and development. Data of all kinds.

  • Finance
  • Music
  • Number
  • Person
  • Git
  • Airline
  • Animal
  • Phone
  • Internet
  • Color
  • Image
  • Commerce
  • Company
  • Vehicle
  • Location
  • Products

So, let's learn how to create mock data for your Angular unit tests.

Ready?

mock-data

1. Install Faker

npm install @faker-js/faker --save-dev

2. Generate simple fake name

Say we need a simple full name for our test. We would import faker.

import { faker } from '@faker-js/faker';

And then use it to generate a name.

const name = faker.person.fullName();

A unit test in Angular would look like this.

it(`should have the 'ng-playground' title`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;

    const expected = faker.person.fullName();
    expect(app.title).toEqual(expected);
});

Here's the result.

faker-angular-mock-name

3. Generate fake data for an interface

Say that we have an interface called Person.

export interface Person {
    firstName: string;
    lastName: string;
    email: string;
    bio: string;
    phoneNumber: string;
}

And we need to generate a mock Person object for our test.

Here's our test.

it('should accept person as input', () => {
    const person = {
      firstName: faker.person.firstName(),
      lastName: faker.person.lastName(),
      bio: faker.person.bio(),
      email: faker.internet.email(),
      phoneNumber: faker.phone.number()
    } as Person;

    const fixture = TestBed.createComponent(AppComponent);
    fixture.componentInstance.person = person;

    expect(fixture.componentInstance.person).toEqual(person);
  });

Conclusion

And that, my friend, is how to use Faker and Angular to generate mock data for your unit tests.

A huge shout out to the Faker library! 👏

Till later,

signature

Daniel Kreider