
JavaScript应用测试的数据建模和关系模拟库
@mswjs/data是一个JavaScript应用测试库,提供数据建模和关系模拟功能。它允许开发者直观地创建数据模 型、建立模型间关系,并通过类数据库方式查询数据。该库支持与REST和GraphQL API模拟集成,有助于简化原型设计和测试流程。
When testing API interactions you often need to mock data. Instead of keeping a hard-coded set of fixtures, this library provides you with must-have tools for data-driven API mocking:
$ npm install @mswjs/data --save-dev # or $ yarn add @mswjs/data --dev
With this library, you're modeling data using the factory function. That function accepts an object where each key represents a model name and the values are model definitions. A model definition is an object where the keys represent model properties and the values are value getters.
// src/mocks/db.js import { factory, primaryKey } from '@mswjs/data' export const db = factory({ // Create a "user" model, user: { // ...with these properties and value getters. id: primaryKey(() => 'abc-123'), firstName: () => 'John', lastName: () => 'Maverick', }, })
See the Recipes for more guidelines on data modeling.
Throughout this document native JavaScript constructors (i.e. String, Number) will be used as values getters for the models, as they both create a value and define its type. In practice, you may consider using value generators or tools like Faker for value getters.
Each model must have a primary key. That is a root-level property representing the model's identity. Think of it as an "id" column for a particular table in a database.
Declare a primary key by using the primaryKey function:
import { factory, primaryKey } from '@mswjs/data' factory({ user: { id: primaryKey(String), }, })
In the example above, the id is the primary key for the user model. This means that whenever a user is created it must have the id property that equals a unique String. Any property can be marked as a primary key, it doesn't have to be named "id".
Just like regular model properties, the primary key accepts a getter function that you can use to generate its value when creating entities:
import { faker } from '@faker-js/faker' factory({ user: { id: primaryKey(faker.datatype.uuid), }, })
Each time a new
useris created, itsuser.idproperty is seeded with the value returned from thedatatype.uuidfunction call.
Once your data is modeled, you can use Model methods to interact with it (create/update/delete). Apart from serving as interactive, queryable fixtures, you can also integrate your data models into API mocks to supercharge your prototyping/testing workflow.
factoryThe factory function is used to model a database. It accepts a model dictionary and returns an API to interact with the described models.
import { factory, primaryKey } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), firstName: String, age: Number, }, })
Learn more about the Model methods and how you can interact with the described models.
Each factory call encapsulates an in-memory database instance that holds the respective models. It's possible to create multiple database instances by calling factory multiple times. The entities and relationships, however, are not shared between different database instances.
primaryKeyMarks the property of a model as a primary key.
import { factory, primaryKey } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), }, }) // Create a new "user" with the primary key "id" equal to "user-1". db.user.create({ id: 'user-1' })
Primary key must be unique for each entity and is used as the identifier to query a particular entity.
nullableMarks the current model property as nullable.
import { factory, primaryKey, nullable } from '@mswjs/data' factory({ user: { id: primaryKey(String) // "user.title" is a nullable property. title: nullable(String) } })
Learn more how to work with Nullable properties.
oneOfCreates a *-to-one relationship with another model.
import { factory, primaryKey, oneOf } from '@mswjs/data' factory({ user: { id: primaryKey(String), role: oneOf('userGroup'), }, userGroup: { name: primaryKey(String), }, })
Learn more about Modeling relationships.
manyOfCreates a *-to-many relationship with another model.
import { factory, primaryKey, manyOf } from '@mswjs/data' factory({ user: { id: primaryKey(String), publications: manyOf('post'), }, post: { id: primaryKey(String), title: String, }, })
Learn more about Modeling relationships.
dropDeletes all entities in the given database instance.
import { factory, drop } from '@mswjs/data' const db = factory(...models) drop(db)
Each model has the following methods:
create()findFirst()findMany()count()getAll()update()updateMany()delete()deleteMany()toHandlers()createCreates an entity for the model.
const user = db.user.create()
When called without arguments, .create() will populate the entity properties using the getter functions you've specified in the model definition.
You can also provide a partial initial values when creating an entity:
const user = db.user.create({ firstName: 'John', })
Note that all model properties are optional, including relational properties.
findFirstReturns the first entity that satisfies the given query.
const user = db.user.findFirst({ where: { id: { equals: 'abc-123', }, }, })
findManyReturns all the entities that satisfy the given query.
const users = db.user.findMany({ where: { followersCount: { gte: 1000, }, }, })
countReturns the number of records for the given model.
db.user.create() db.user.create() db.user.count() // 2
Can accept an optional query argument to filter the records before counting them.
db.user.count({ where: { role: { equals: 'reader', }, }, })
getAllReturns all the entities of the given model.
const allUsers = db.user.getAll()
updateUpdates the first entity that matches the query.
const updatedUser = db.user.update({ // Query for the entity to modify. where: { id: { equals: 'abc-123', }, }, // Provide partial next data to be // merged with the existing properties. data: { // Specify the exact next value. firstName: 'John', // Alternatively, derive the next value from // the previous one and the unmodified entity. role: (prevRole, user) => reformatRole(prevRole), }, })
updateManyUpdates multiple entities that match the query.
const updatedUsers = db.user.updateMany({ // Query for the entity to modify. where: { id: { in: ['abc-123', 'def-456'], }, }, // Provide partial next data to be // merged with the existing properties. data: { firstName: (firstName) => firstName.toUpperCase(), }, })
deleteDeletes the entity that satisfies the given query.
const deletedUser = db.user.delete({ where: { followersCount: { equals: 0, }, }, })
deleteManyDeletes multiple entities that match the query.
const deletedUsers = db.user.deleteMany({ where: { followersCount: { lt: 10, }, }, })
toHandlersGenerates request handlers for the given model to use with Mock Service Worker. All generated handlers are automatically connected to the respective model methods, enabling you to perform CRUD operations against your mocked database.
import { factory, primaryKey } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), firstName: String, }, }) // Generates REST API request handlers. db.user.toHandlers('rest')
import { factory, primaryKey } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), firstName: String, }, }) // Generates GraphQL API request handlers. db.user.toHandlers('graphql')
The .toHandlers() method supports an optional second baseUrl argument to scope the generated handlers to a given endpoint:
db.user.toHandlers('rest', 'https://example.com') db.user.toHandlers('graphql', 'https://example.com/graphql')
By default, all model properties are non-nullable. You can use the nullable function to mark a property as nullable:
import { factory, primaryKey, nullable } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), firstName: String, // "user.age" is a nullable property. age: nullable(Number), }, }) db.user.create({ id: 'user-1', firstName: 'John', // Nullable properties can be explicit null as the initial value. age: null, }) db.user.update({ where: { id: { equals: 'user-1', }, }, data: { // Nullable properties can be updated to null. age: null, }, })
You can define Nullable relationships in the same manner.
When using Typescript, you can manually set the type of the property when it cannot be otherwise inferred from the seeding function, such as when you want a property to default to null:
import { factory, primaryKey, nullable } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), age: nullable<number>(() => null), }, })
You may use nested objects to design a complex structure of your model:
import { factory, primaryKey, nullable } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), address: { billing: { street: String, city: nullable(String), }, }, }, }) // You can then create and query your data // based on the nested properties. db.user.create({ id: 'user-1', address: { billing: { street: 'Baker st.', city: 'London', }, }, }) db.user.update({ where: { id: { equals: 'user-1', }, }, data: { address: { billing: { street: 'Sunwell ave.', city: null, }, }, }, })
Note that you cannot mark a nested property as the primary key.
You may also specify relationships nested deeply in your model:
factory({ user: { id: primaryKey(String), address: { billing: { country: oneOf('country'), }, }, }, country: { code: primaryKey(String), }, })
Learn more about Model relationships.
Relationship is a way for a model to reference another model.
import { factory, primaryKey, oneOf } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), firstName: String, }, post: { id: primaryKey(String), title: String, // The "post.author" references a "user" model. author: oneOf('user'), }, }) const user = db.user.create({ firstName: 'John' }) const post = db.post.create({ title: 'My journey', // Use a "user" entity as the actual value of this post's author. author: user, }) post.author.firstName // "John"
import { factory, primaryKey, manyOf } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), // "user.posts" is a list of the "post" entities. posts: manyOf('post'), }, post: { id: primaryKey(String), title: String, }, }) const posts = [ db.post.create({ title: 'First' }), db.post.create({ title: 'Second' }), ] const user = db.user.create({ // Assign the list of existing posts to this user. posts, }) user.posts // [{ title: "First" }, { title: "Second" }]
import { factory, primaryKey, oneOf } from '@mswjs/data' const db = factory({ country: { name: primaryKey(String), }, user: { id: primaryKey(String), country: oneOf('country'), }, car: { serialNumber: primaryKey(String), country: oneOf('country'), }, }) const usa = db.country.create({ name: 'The United States of America' }) // Create a "user" and a "car" with the same country. db.user.create({ country: usa }) db.car.create({ country: usa })
Both oneOf and manyOf relationships may be marked as unique. A unique relationship is where a referenced entity cannot be assigned to another entity more than once.
In the example below we define the "user" and "invitation" models, and design their relationship so that one invitation cannot be assigned to multiple users.
import { factory, primaryKey, oneOf } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), invitation: oneOf('invitation', { unique: true }), }, invitation: { id: primaryKey(String), }, }) const invitation = db.invitation.create() const john = db.user.create({ invitation }) // Assigning the invitation already used by "john" // will throw an exception when creating this entity. const karl = db.user.create({ invitation })
Both oneOf and manyOf relationships may be passed to nullable to allow
instantiating and updating that relation to null.
import { factory, primaryKey, oneOf, nullable } from '@mswjs/data' const db = factory({ user: { id: primaryKey(String), invitation: nullable(oneOf('invitation')), friends: nullable(manyOf('user')), }, invitation: { id: primaryKey(String), }, }) const invitation = db.invitation.create() // Nullable relationships are instantiated with null. const john = db.user.create({ invitation }) // john.friends === null const kate = db.user.create({ friends: [john] }) // kate.invitation === null db.user.updateMany({ where: { id: { in: [john.id, kate.id], }, }, data: { // Nullable relationships can be updated to null. invitation: null, friends: null, }, })
This library supports querying of the seeded data similar to how one would query a SQL database. The data is queried based on its properties. A query you construct depends on the value type you are querying.
equalsnotEqualscontainsnotContainsinnotInequalsnotEqualsgtgteltltebetweennotBetweeninnotInequals

多风格AI绘画神器
堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。


零代码AI应用开发平台
零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5 网页应用,无需编写代码。


免费创建高清无水印Sora视频
Vora是一个免费创建高清无水印Sora视频的AI工具


最适合小白的AI自动化工作流平台
无需编码,轻松生成可复用、可变现的AI自动化工作流

大模型驱动的Excel数据处理工具
基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。


AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目 交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


AI论文写作指导平台
AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。


AI一键生成PPT,就用博思AIPPT!
博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。


AI赋能电商视觉革命,一站式智能商拍平台
潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。


企业专属的AI法律顾问
iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。
最新AI工具、AI资讯
独家AI资源、AI项目落地

微信扫一扫关注公众号