courteousturtle
courteousturtle

Reputation: 11

How do I wait for oclif command output which makes an async rest API call for testing?

I'm trying to test an OCLIF app, said app uses superAgent within a command(execute) and it all works as I intend. The issue is with testing the command. I've been trying to use both oclif/test and native jest to no luck. I'm sure I'm not understanding something clearly.

If someone could help I'd greatly appreciate it.

My command is named execute which has an async(run) method, from this method I call await mangageRequest(flags) - that's another function I've written (the snippet below is from within manageRequest()). manageRequest also looks returns a Promise

The command snippet :

        console.log(`---- Running fooTask task : ${params.task} ------\n`)
        hosts.forEach((hostToExecuteAgainst) => {
                request.post(hostToExecuteAgainst)
                .query(params.options)
                .send(params.body)
                .type(params.headers)
                .buffer(true)
                .parse(request.parse.text)
                .end(function(err,res) {
                    requestsCompleted = requestsCompleted ++
                    console.log(`--- Server Response :: ---\n${res.text}`)
                    if (err) {
                        requestFailed = true
                        console.error(`The execution failed for : ${hostToExecuteAgainst} with error : ${err} and details : ${err.body}`)
                    }


                    if(requestsCompleted == hosts.length) {
                        if (requestFailed) {
                            throw new Error(`One or more tasks failed : refer to logs`)
                        }
                    }

                    
                })
        })

using oclif test 1

    test
    .nock('http://127.0.0.1:5001', api => api
        .post('/tasks/gc')
        .reply(200, "GC ran successfully")
    )
    .stdout()
    .command(['execute', '--run', '--task=log-level', '--httpHosts=127.0.0.1:5001'])
    .it('Query with params - run 1', (result) => {
        console.log(result.stdout)
        expect(result.toString()).to.contain('GC ran successfully')

    } )

using jest

describe('Test Command', () => {
    let result;

    beforeEach(() => {
        result = [];
        jest
            .spyOn(process.stdout, 'write')
            .mockImplementation(val =>
                result.push(val)
            );
    });

    afterEach(() => jest.restoreAllMocks());


    it('GC with run', async () => {

        //setup nocked mock
        const scope = nock('http://127.0.0.1:7001')
        .post('/tasks/gc')
        .reply(200, 'GC ran successfully')

        await Execute.run(['--httpHosts=127.0.0.1:7001', '--task=gc','--run']);
        //await expect(result.toString()).toContain('Task : gc')
        expect(result).toContain('GC ran successfully')
    });
});

instead of what I expect I receive this : firstly my test fail ( both tests ) secondly,

Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log "--- Server Response :: ---
    GC ran successfully.

I know that I'm not waiting on the execution but I'm waiting on the command to finish, which is waiting on manageRequest, so I should get the response? ( well obviously there's a gap in my understanding and hence this question ). None of the methods return anything ( oclif command doesn't return anything just logs )

P.S - I read through How can I test oclif CLI that consumes Rest API , https://snyk.io/advisor/npm-package/superagent/functions/superagent.parse and https://martianwabbit.com/2018/05/25/testing-oclif-with-jest.html etc

Upvotes: 0

Views: 135

Answers (0)

Related Questions