UNPKG

@serenity-js/core

Version:

The core Serenity/JS framework, providing the Screenplay Pattern interfaces, as well as the test reporting and integration infrastructure

220 lines 10.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Actor = void 0; const errors_1 = require("../errors"); const events_1 = require("../events"); const io_1 = require("../io"); const model_1 = require("../model"); const abilities_1 = require("./abilities"); /** * **Actors** represent **people** and **external systems** interacting with the system under test. * Their role is to perform [activities](https://serenity-js.org/api/core/class/Activity/) that demonstrate how to accomplish a given goal. * * Actors are the core building block of the [Screenplay Pattern](https://serenity-js.org/handbook/design/screenplay-pattern), * along with [abilities](https://serenity-js.org/api/core/class/Ability/), [interactions](https://serenity-js.org/api/core/class/Interaction/), [tasks](https://serenity-js.org/api/core/class/Task/), and [questions](https://serenity-js.org/api/core/class/Question/). * Actors are also the first thing you see in a typical Serenity/JS test scenario. * * ![Screenplay Pattern](https://serenity-js.org/images/design/serenity-js-screenplay-pattern.png) * * Learn more about: * - [`Cast`](https://serenity-js.org/api/core/class/Cast/) * - [`Stage`](https://serenity-js.org/api/core/class/Stage/) * - [`Ability`](https://serenity-js.org/api/core/class/Ability/) * - [`Activity`](https://serenity-js.org/api/core/class/Activity/) * - [`Interaction`](https://serenity-js.org/api/core/class/Interaction/) * - [`Task`](https://serenity-js.org/api/core/class/Task/) * - [`Question`](https://serenity-js.org/api/core/class/Question/) * * ## Representing people and systems as actors * * To use a Serenity/JS [`Actor`](https://serenity-js.org/api/core/class/Actor/), all you need is to say their name: * * ```typescript * import { actorCalled } from '@serenity-js/core' * * actorCalled('Alice') * // returns: Actor * ``` * * Serenity/JS actors perform within the scope of a test scenario, so the first time you invoke [`actorCalled`](https://serenity-js.org/api/core/function/actorCalled/), * Serenity/JS instantiates a new actor from the default [cast](https://serenity-js.org/api/core/class/Cast/) of actors (or any custom cast you might have [configured](https://serenity-js.org/api/core/function/configure/)). * Any subsequent invocations of this function within the scope of the same test scenario retrieve the already instantiated actor, identified by their name. * * ```typescript * import { actorCalled } from '@serenity-js/core' * * actorCalled('Alice') // instantiates Alice * actorCalled('Bob') // instantiates Bob * actorCalled('Alice') // retrieves Alice, since she's already been instantiated * ``` * * Serenity/JS scenarios can involve as many or as few actors as you need to model the given business workflow. * For example, you might want to use **multiple actors** in test scenarios that model how **different people** perform different parts of a larger business process, such as reviewing and approving a loan application. * It is also quite common to introduce **supporting actors** to perform **administrative tasks**, like setting up test data and environment, or **audit tasks**, like checking the logs or messages emitted to a message queue * by the system under test. * * :::info The Stan Lee naming convention * Actor names can be much more than just simple identifiers like `Alice` or `Bob`. While you can give your actors any names you like, a good convention to follow is to give them * names indicating the [personae](https://articles.uie.com/goodwin_interview/) they represent or the role they play in the system. * * Just like the characters in [Stan Lee](https://en.wikipedia.org/wiki/Stan_Lee) graphic novels, * actors in Serenity/JS test scenarios are often given alliterate names as a mnemonic device. * Names like "Adam the Admin", "Edna the Editor", "Trevor the Traveller", are far more memorable than a generic "UI user" or "API user". * They're also much easier for people to associate with the context, constraints, and affordances of the given actor. * ::: * * @group Screenplay Pattern */ class Actor { name; stage; abilities = new Map(); constructor(name, stage, abilities = []) { this.name = name; this.stage = stage; [ new abilities_1.PerformActivities(this, stage), new abilities_1.AnswerQuestions(this), ...abilities ].forEach(ability => this.acquireAbility(ability)); } /** * Retrieves actor's [`Ability`](https://serenity-js.org/api/core/class/Ability/) of `abilityType`, or one that extends `abilityType`. * * Please note that this method performs an [`instanceof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) check against abilities * given to this actor via [`Actor.whoCan`](https://serenity-js.org/api/core/class/Actor/#whoCan). * * Please also note that [`Actor.whoCan`](https://serenity-js.org/api/core/class/Actor/#whoCan) performs the same check when abilities are assigned to the actor * to ensure the actor has at most one instance of a given ability type. * * @param abilityType */ abilityTo(abilityType) { const found = this.findAbilityTo(abilityType); if (!found) { throw new errors_1.ConfigurationError(`${this.name} can ${Array.from(this.abilities.keys()).map(type => type.name).join(', ')}. ` + `They can't, however, ${abilityType.name} yet. ` + `Did you give them the ability to do so?`); } return found; } /** * Instructs the actor to attempt to perform a number of [activities](https://serenity-js.org/api/core/class/Activity/), * so either [tasks](https://serenity-js.org/api/core/class/Task/) or [interactions](https://serenity-js.org/api/core/class/Interaction/)), * one by one. * * @param {...activities: Activity[]} activities */ attemptsTo(...activities) { return activities .reduce((previous, current) => { return previous .then(() => abilities_1.PerformActivities.as(this).perform(current)); }, this.initialiseAbilities()); } /** * Gives this Actor a list of [abilities](https://serenity-js.org/api/core/class/Ability/) they can use * to interact with the system under test or the test environment. * * @param abilities * A vararg list of abilities to give the actor * * @returns * The actor with newly gained abilities * * @throws [`ConfigurationError`](https://serenity-js.org/api/core/class/ConfigurationError/) * Throws a ConfigurationError if the actor already has an ability of this type. */ whoCan(...abilities) { abilities.forEach(ability => this.acquireAbility(ability)); return this; } /** * @param answerable - * An [`Answerable`](https://serenity-js.org/api/core/#Answerable) to answer (resolve the value of). * * @returns * The answer to the Answerable */ answer(answerable) { return abilities_1.AnswerQuestions.as(this).answer(answerable); } /** * @inheritDoc */ collect(artifact, name) { this.stage.announce(new events_1.ActivityRelatedArtifactGenerated(this.stage.currentSceneId(), this.stage.currentActivityId(), this.nameFrom(name || new model_1.Name(artifact.constructor.name)), artifact, this.stage.currentTime())); } /** * Returns current time. */ currentTime() { return this.stage.currentTime(); } /** * Instructs the actor to invoke [`Discardable.discard`](https://serenity-js.org/api/core/interface/Discardable/#discard) method on any * [discardable](https://serenity-js.org/api/core/interface/Discardable/) [ability](https://serenity-js.org/api/core/class/Ability/) it's been configured with. */ dismiss() { return this.findAbilitiesOfType('discard') .reduce((previous, ability) => previous.then(() => ability.discard()), Promise.resolve(void 0)); } /** * Returns a human-readable, string representation of this actor and their abilities. * * **PRO TIP:** To get the name of the actor, use [`Actor.name`](https://serenity-js.org/api/core/class/Actor/#name) */ toString() { const abilities = Array.from(this.abilities.values()).map(ability => ability.constructor.name); return `Actor(name=${this.name}, abilities=[${abilities.join(', ')}])`; } /** * Returns a JSON representation of the actor and its current state. * * The purpose of this method is to enable reporting the state of the actor in a human-readable format, * rather than to serialise and deserialise the actor itself. */ toJSON() { return { name: this.name, abilities: Array.from(this.abilities.values()).map(ability => ability.toJSON()) }; } initialiseAbilities() { return this.findAbilitiesOfType('initialise', 'isInitialised') .filter(ability => !ability.isInitialised()) .reduce((previous, ability) => previous .then(() => ability.initialise()) .catch(error => { throw new errors_1.TestCompromisedError(`${this.name} couldn't initialise the ability to ${ability.constructor.name}`, error); }), Promise.resolve(void 0)); } findAbilitiesOfType(...methodNames) { const abilitiesFrom = (map) => Array.from(map.values()); const abilitiesWithDesiredMethods = (ability) => methodNames.every(methodName => typeof (ability[methodName]) === 'function'); return abilitiesFrom(this.abilities) .filter(abilitiesWithDesiredMethods); } findAbilityTo(doSomething) { return this.abilities.get(doSomething.abilityType()); } acquireAbility(ability) { if (!(ability instanceof abilities_1.Ability)) { throw new errors_1.ConfigurationError(`Custom abilities must extend Ability from '@serenity-js/core'. Received ${io_1.ValueInspector.typeOf(ability)}`); } this.abilities.set(ability.abilityType(), ability); } /** * Instantiates a `Name` based on the string value of the parameter, * or returns the argument if it's already an instance of `Name`. * * @param maybeName */ nameFrom(maybeName) { return typeof maybeName === 'string' ? new model_1.Name(maybeName) : maybeName; } } exports.Actor = Actor; //# sourceMappingURL=Actor.js.map