Skip to main content

respondOnce

Overview

Use the respondOnce command to respond once with the specified overwrite.

You can call respondOnce multiple times in succession. The responses will be used in the same order the respondOnce commands were called.

If you use only respondOnce and access the resource more times than respondOnce was called, then after exhausting the fake data, the request will start returning the original response from the resource.

Usage

mock.respondOnce(overwrites, { header, statusCode, fetchResponse });

Command Parameters

NameTypeDescription
overwritesMockOverwritePayload to overwrite the response.
headerObjectOverwrite specific headers.
statusCodeNumberOverwrite the response status code.
fetchResponseBooleanFetch the actual response before replying with fake data.

Usage Examples

async function getToDos(browser) {
await browser.$("#todo-list li").waitForExist();

const todoElements = await browser.$$("#todo-list li");

return Promise.all(todoElements.map(el => el.getText()));
}

it("should demonstrate the respondOnce command", async ({ browser }) => {
const mock = await browser.mock("https://todo-backend-express-knex.herokuapp.com/", {
method: "get",
});

mock.respondOnce([
{
title: "3",
},
{
title: "2",
},
{
title: "1",
},
]);

mock.respondOnce([
{
title: "2",
},
{
title: "1",
},
]);

mock.respondOnce([
{
title: "1",
},
]);

await browser.url(
"https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/",
);
console.log(await getToDos(browser)); // outputs: [ '3', '2', '1' ]

await browser.url(
"https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/",
);
console.log(await getToDos(browser)); // outputs: [ '2', '1' ]

await browser.url(
"https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/",
);
console.log(await getToDos(browser)); // outputs: [ '1' ]

await browser.url(
"https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/",
);
console.log(await getToDos(browser)); // outputs: the actual resource response
});

References

We'd like to give credit to the original WebdriverIO docs article, from which we drew some information while writing our version.