Product
Introducing SSO
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
botbuilder-unit
Advanced tools
Readme
The Library still in an active development, so don't hesitate to propose changes and new features! Backward compatibility of API not guaranteed before 1.0 release.
This is a test framework for chatbots developed with Microsoft Bot Framework for Node.JS. Supports both unit and functional tests. In background of MBF
Emulates a conversation between user and bot. Provides input for bot and validates response. Each test requires a script - array of steps, where every step represents of next entities:
Test fails if conversation deviates from specified in script.
I apologize for the inconvenience.
Support bots (for functional tests) and dialogs (unit testing);
Built-in validators:
session state management;
active dialog and default params management;
timeout validation;
custom validation login as a step of the script
configurable reporting;
mocking of responses from a bot, use it if you need only to prototype conversation;
npm install --save-dev botbuilder-unit
File "test-script.js":
const unit = require('botbuilder-unit');
const builder = require('botbuilder');
// This array, also called a script. It will be used to validate conversation with user
let script = [
{
"user": "hi"
},
{
"bot": "How should I call you?"
},
{
"user": "Timmy"
},
{
"bot": "Nice to meet you, \"Timmy\"!"
}
];
// Setting up a bot
bot = new builder.UniversalBot(connector);
bot.dialog('/', [
session => builder.Prompts.text(session, 'How should I call you?'),
(session, response) => session.endDialog(`Nice to meet you, ${JSON.stringify(response.response)}!`)
]);
// Executing test
unit(bot, script, {
title: 'Your first test script',
reporter : new unit.BeautyLogReporter() // Display log in messenger-like style, with colors
}).then(() => {
// If test finished successfully
console.log('Script passed');
}, (err) => {
console.error(err);
})
node ./test-script.js
At the end you will see next result:
npm install --save-dev botbuilder-unit
As already mentioned, all steps are divided into groups of activities, each step is key-value object. Each activity defines a set of unique keys. So, the Library differentiates steps key used in a step configuration.
Each key represents a concrete action. Some keys could used together, in one step. If key name marked as standalone, that means the key always alone in a step. It is not possible to mix key of different activities.
Full list of supported step attributes:
Bot Response Validation. :
Input from User:
Session Management:
Dialog Management:
dialog, sets current dialog for bot instance, could be used together with args option
args, set default arguments for bot instance, could be used together with dialog option
If the message is from the user, than message object should look like this:
{
"user" : "Hey there!"
}
Or, specify a filter function. The Library will pass an argument to the function - an instance of bot being tested. A function must return a Promise. An resolved value of Promise (supposed to be a string) will be passed to the bot:
{
"user": function () {
return Promise.resolve('Hello world!');
}
}
In case, if the message is from the bot, than:
{
"bot" : "Hello, %username%"
}
It is possible to validate bot messages with RegExps:
{
"bot" : /^Hello/
}
or with a filter function. The Library will pass two arguments into the function:
Next example presents usage of filter function, that validates if chatbot returned a Number in range of 0 to 100:
{
"bot" : function ( receivedMessage) {
let value = parseInt(receivedMessage.text);
if (( value >= 0 ) && (value <=100)) {
return Promise.resolve('success');
} else {
return Promise.reject('failure');
}
}
}
If you want to validate suggested actions of the message:
{
"bot" : "Hello world!",
"suggestedActions" : [
botbuilder.CardAction.imBack(null, "add", "Add"),
botbuilder.CardAction.imBack(null, "settings", "Settings")
]
}
You could use filter function to validate suggested actions:
{
"bot" : function ( receivedMessage ) {
if ( receviedMessage.suggestedActions.length == 2 ) {
return Promise.resolve('success');
} else {
return Promise.reject('fail');
}
}
}
It is possible to validate attachments and richcards returned by a bot. To validate attachment body you need to specify a step with attachments attribute, to validate an attachment layout you need to specify attachmentLayout attribute.
It is possible to combine these parameters together.
{
"attachmentLayout": "carousel",
"attachments": [
{
"contentType": "application/vnd.microsoft.card.hero",
"content": {
"title": "My Title",
"subtitle": "My Subtitle",
"images": [
{
"url": "Some Url"
},
{
"url": "Another Url"
}
]
}
}
]
},
Or with bot attribute:
{
"bot" : "Hello World!",
"attachmentLayout": "carousel",
"attachments": [
{
"contentType": "application/vnd.microsoft.card.hero",
"content": {
"title": "My Title",
"subtitle": "My Subtitle",
"images": [
{
"url": "Some Url"
},
{
"url": "Another Url"
}
]
}
}
]
},
Inside attachments body you could freely use filter functions. The function will receive a part of attachments object body for validation:
{
"bot" : "World!",
"attachmentLayout": function ( value ) {
return "carousel" == value ? Promise.resolve() : Promise.reject();
},
"attachments": [
{
"contentType": "application/vnd.microsoft.card.hero",
"content": {
"title": function ( value ) {
return "My Title" == value ? Promise.resolve() : Promise.reject('Wrong title');
},
"subtitle": function (value ) {
return "My Subtitle" == value ? Promise.resolve() : Promise.reject('Wrong subtitle');
},
"images": function ( value ) {
return 2 == value.length ? Promise.resolve() : Promise.reject('Wrong images count');
}
}
}
]
}
It is possible to setup a state for session:
{
"session" : {userData: {userName : 'Joe'}}
}
Another option is to specify a filter function. Current session object will be passed as a first argument into the filter:
{
"session" : function (session) {
session.userDta.userName = 'Joe';
return Promise.resolve(session);
}
}
Example:
{
"endConversation" : true
}
More about ending conversation you could find in official documentation.
Example:
{
"typing": true
}
It is possible to inject a custom step into the script. Such step contains a user-defined filter function (in attribute custom)_ that MUST return a Promise object.
Once, when the Promise will appear resolved/rejected state:
Example:
{
"custom": function () {
if ( someValidationFunc() ) {
return Promise.resolve();
} else {
return Promise.reject('Custom validation failed');
}
}
}
You could specify a dialog id that will be set as active or default dialog for the bot. In case, if you call that function in the middle of conversation (when session conversation object already created) this message will replace See an Example:
It is also possible to specify an arguments to the function:
Important! the message produces a side effect as the function manipulates with attributes: settings.defaultDialogId and settings.defaultDialogArgs
You also could specify a filter function. The Library will pass current instance of bot as argument into the function:
Global options will be applied to every script that will be processed by library. There are two ways to setup a global option:
For example, to run script with 10 seconds timeout and beautified output you need to execute something like:
export BOTBUILDERUNIT_REPORTER=beauty; export BOTBUILDERUNIT_TEST_TIMEOUT=10000; npm test
The library exposes config
object in module.exports. Properties of an object:
unit(bot , script, options) or unit(dialog, script, options) - Tests given bot instance or dialog with script. Returns a Promise that will be resolved in case of success. Method arguments:
key | description |
---|---|
title | String or null, value that represents test title. Will be rendered in test report |
timeout | Integer, allowed execution time for a test |
reporter | intance of BaseLogReporter, an log reporter instance, overwrites default log reporter |
Library provides an ConversationMock class with purpose to mock responses from the chatbot. Possible use cases for such feature are:
Where steps is an array of standard waterfall dialog functions. Each step will be executed only once. The Library will pass standard arguments: session, arguments,next into step.
sendMessagesStep( messages, afterFunc) - Creates a step for waterfall dialog. Arguments:
FAQs
Unit tests for chatbot dialogs
The npm package botbuilder-unit receives a total of 2,151 weekly downloads. As such, botbuilder-unit popularity was classified as popular.
We found that botbuilder-unit demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.