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.
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`)
}
}
})
})
command -> async(run) -> here I call await mangageRequest(flags)
(within manageRequest I’ve written the snippet above ). manageRequest
also looks returns a promise
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