ApiDataFactory
ApiDataFactory
Section titled “ApiDataFactory”Extends Helper
Helper for managing remote data using REST API. Uses data generators like rosie or factory girl to create new record.
By defining a factory you set the rules of how data is generated. This data will be saved on server via REST API and deleted in the end of a test.
Use Case
Section titled “Use Case”Acceptance tests interact with a websites using UI and real browser. There is no way to create data for a specific test other than from user interface. That makes tests slow and fragile. Instead of testing a single feature you need to follow all creation/removal process.
This helper solves this problem. Most of web application have API, and it can be used to create and delete test records. By combining REST API with Factories you can easily create records for tests:
I.have('user', { login: 'davert', email: 'davert@mail.com' });let id = await I.have('post', { title: 'My first post'});I.haveMultiple('comment', 3, {post_id: id});To make this work you need
- REST API endpoint which allows to perform create / delete requests and
- define data generation rules
Install Rosie and Faker libraries.
npm i rosie @faker-js/faker --save-devCreate a factory file for a resource.
See the example for Posts factories:
const { Factory } = require('rosie');const { faker } = require('@faker-js/faker');
module.exports = new Factory() // no need to set id, it will be set by REST API .attr('author', () => faker.person.findName()) .attr('title', () => faker.lorem.sentence()) .attr('body', () => faker.lorem.paragraph());For more options see rosie documentation.
Then configure ApiDataHelper to match factories and REST API:
Configuration
Section titled “Configuration”ApiDataFactory has following config options:
endpoint: base URL for the API to send requests to.cleanup(default: true): should inserted records be deleted up after testsfactories: list of defined factoriesreturnId(default: false): return id instead of a complete response when creating items.headers: list of headersREST: configuration for REST requests
See the example:
ApiDataFactory: { endpoint: "http://user.com/api", cleanup: true, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, factories: { post: { uri: "/posts", factory: "./factories/post", }, comment: { factory: "./factories/comment", create: { post: "/comments/create" }, delete: { post: "/comments/delete/{id}" }, fetchId: (data) => data.result.id } }}It is required to set REST API endpoint which is the baseURL for all API requests.
Factory file is expected to be passed via factory option.
This Helper uses REST helper and accepts its configuration in “REST” section. For instance, to set timeout you should add:
"ApiDataFactory": { "REST": { "timeout": "100000", }}Requests
Section titled “Requests”By default to create a record ApiDataFactory will use endpoint and plural factory name:
- create:
POST {endpoint}/{resource} data - delete:
DELETE {endpoint}/{resource}/id
Example (endpoint: http://app.com/api):
- create: POST request to
http://app.com/api/users - delete: DELETE request to
http://app.com/api/users/1
This behavior can be configured with following options:
uri: set different resource uri. Example:uri: account=>http://app.com/api/account.create: override create options. Expected format:{ method: uri }. Example:{ "post": "/users/create" }delete: override delete options. Expected format:{ method: uri }. Example:{ "post": "/users/delete/{id}" }
Requests can also be overridden with a function which returns axois request config.
create: (data) => ({ method: 'post', url: '/posts', data }),delete: (id) => ({ method: 'delete', url: '/posts', data: { id } })Requests can be updated on the fly by using onRequest function. For instance, you can pass in current session from a cookie.
onRequest: async (request) => { // using global codeceptjs instance let cookie = await codeceptjs.container.helpers('WebDriver').grabCookie('session'); request.headers = { Cookie: `session=${cookie.value}` }; }Responses
Section titled “Responses”By default I.have() returns a promise with a created data:
let client = await I.have('client');Ids of created records are collected and used in the end of a test for the cleanup.
If you need to receive id instead of full response enable returnId in a helper config:
// returnId: falselet clientId = await I.have('client');// clientId == 1
// returnId: truelet clientId = await I.have('client');// client == { name: 'John', email: 'john@snow.com' }By default id property of response is taken. This behavior can be changed by setting fetchId function in a factory config.
factories: { post: { uri: "/posts", factory: "./factories/post", fetchId: (data) => data.result.posts[0].id } }Methods
Section titled “Methods”Parameters
Section titled “Parameters”config
_requestCreate
Section titled “_requestCreate”Executes request to create a record in API. Can be replaced from a in custom helper.
Parameters
Section titled “Parameters”factoryanydataany
_requestDelete
Section titled “_requestDelete”Executes request to delete a record in API Can be replaced from a custom helper.
Parameters
Section titled “Parameters”factoryanyidany
Generates a new record using factory and saves API request to store it.
// create a userI.have('user');// create user with defined email// and receive it when inside async functionconst user = await I.have('user', { email: 'user@user.com'});// create a user with options that will not be included in the final requestI.have('user', { }, { age: 33, height: 55 })Parameters
Section titled “Parameters”factoryany factory to useparamsany? predefined parametersoptionsany? options for programmatically generate the attributes
Returns Promise
haveMultiple
Section titled “haveMultiple”Generates bunch of records and saves multiple API requests to store them.
// create 3 postsI.haveMultiple('post', 3);
// create 3 posts by one authorI.haveMultiple('post', 3, { author: 'davert' });
// create 3 posts by one author with optionsI.haveMultiple('post', 3, { author: 'davert' }, { publish_date: '01.01.1997' });Parameters
Section titled “Parameters”factoryanytimesanyparamsany?optionsany?