npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@tbosmans/factories-ts

v1.3.2

Published

Factories to help writing specs.

Downloads

1

Readme

Why?

When writing tests, it's important to focus on the specific attributes that are relevant to the test scenario, without getting bogged down in the details of record creation or attribute values. This approach avoids cluttered and hard-to-read tests, and allows developers to write more effective and efficient tests.

How does this work?

This is a TypeScript class named BaseFactory which serves as a base class for other factory classes to be extended from. The class has two generic type parameters, BuildAttributes and CreateAttributes, which are used to define the types of the attributes that can be built and created by the factory respectively.

  • The class has four public methods:

    1. build: This method accepts an optional parameter params of type Partial and returns an object of type BuildAttributes. The method generates a new object using the generate() method, and merges it with the params object (if provided) using the spread operator.
    2. buildMany: This method accepts two parameters, times of type number and params of type Partial which is optional. It returns an array of objects of type BuildAttributes. This method generates an array of length times and maps each element to a new object using the build() method.
    3. create: This method accepts an optional parameter params of type Partial and returns a promise that resolves to an object of type CreateAttributes. This method generates a new object using the build() method and passes it to the save() method to persist the object.
    4. createMany: This method accepts two parameters, times of type number and params of type Partial which is optional. It returns a promise that resolves to an array of objects of type CreateAttributes. This method generates an array of length times using the buildMany() method and saves each object using the save() method.
  • The class also has two protected methods:

    1. save: This method accepts an object of type BuildAttributes and returns a promise that resolves to an object of type CreateAttributes. This method is responsible for persisting the object.
    2. generate: This method returns an object of type BuildAttributes. This method is used to generate a new object when the build() method is called without any parameters. The default implementation returns an empty object of type BuildAttributes.

Example in nestjs with prisma and faker:

type BuildAttr = Prisma.UserUncheckedCreateInput
type CreateAttr = User

@Injectable()
export class UserFactory extends BaseFactory<BuildAttr, CreateAttr> {
  constructor(
    private readonly prisma: PrismaService,
    private readonly userRoleFactory: UserRoleFactory,
  ) {}

  protected async save(data: BuildAttr): Promise<CreateAttr> {
    await this.handleRole(data.userRoleId)
    return await this.prisma.user.create({
      data: {
        ...data,
        email: data.email.toLowerCase(),
        password: await hash(data.password, 10),
      },
    })
  }

  // generate random data
  protected generate(): BuildAttr {
    return {
      id: faker.datatype.uuid(),
      email: faker.internet.email(),
      password: faker.internet.password(5),
      firstName: faker.internet.userName(),
      lastName: faker.internet.userName(),
      userRoleId: faker.datatype.uuid(),
      blocked: false,
    }
  }

  // handle relations like for example a role
  private async handleRole(id: UserRole["id"]) {
    const userRole = await this.prisma.userRole.findFirst({ where: { id } })
    if (!userRole) await this.userRoleFactory.create({ id })
  }
}

Now in a jest spec you can do the following:

describe("", () => {
  let module: TestingModule
  let userFactory

  beforeEach(async () => {
    module = // create your testing module
    userFactory = await module.resolve(UserFactory)
  })

  it("does stuff", async () => {
    const user = await userFactory.create({
      email: "[email protected]",
    })
  
    const users = await userFactory.createMany(4, {
      blocked: true
    })
  
    const newUser = userFactory.build()
    const newUsers = userFactory.buildMany()
  })
})