stubOnce behavior / documentation

This issue has been tracked since 2017-11-21.

The docs for stubOnce state: "Stub a response to be used one or more times to respond to a request matching a method and a URL or RegExp.".

From the method name I was expected a different behavior, namely that the response would only used once and subsequent requests would fail.

nicosommi wrote this answer on 2018-01-04

As I want to test a retry mechanism and the error handling regarding that, I also found it confusing since I thought that I was covered with that method.

Anyways, if anyone interested, you can do this by actually manipulating the stubs array right on the main moxios instance.
E.g.

        moxios.stubOnce(
          'put',
          'http://myapi/products/1',
          {}
        )

        let obj = moxios.stubs.mostRecent()
        let count = 0
        Object.defineProperty(obj, 'response', {
          get: () => {
            count++
            if (count > 1) {
              return { status: 200, response: '' }
            }
            return { status: 500, response: '' }
          }
        })

Or maybe is a better way already to do this.
Otherwise I can prepare a PR for this if maintainers are interested @mzabriskie

anilanar wrote this answer on 2018-05-27

Kamino cloned this issue to anilanar/moxios

mrjacobbloom wrote this answer on 2019-06-06

I assumed this function would let me temporarily override an existing stub in the middle of our test suite. Here was what I did instead, in case it helps anyone else:

function overrideStub(url, response) {
    const l = moxios.stubs.count();
    for (let i = 0; i < l; i++) {
        const stub = moxios.stubs.at(i)
        if (stub.url === url) {
            const oldResponse = stub.response;
            const restoreFunc = (() => stub.response = oldResponse);

            stub.response = response;
            return restoreFunc;
        }
    }
}

const restoreStub = overrideStub("../api/foo", {
    status: 500,
    response: 'An error occurred : Bar baz.'
});

buttonThatExpectsError.click();

moxios.wait(() => {
    assert(....);
    restoreStub();
})
More Details About Repo
Owner Name axios
Repo Name moxios
Full Name axios/moxios
Language JavaScript
Created Date 2016-05-25
Updated Date 2022-12-05
Star Count 1386
Watcher Count 20
Fork Count 85
Issue Count 19

YOU MAY BE INTERESTED

Issue Title Created Date Updated Date