I have a function I need to test, it first calls a async function, once received the response then returns a promise to call another function will callback.. Below is the function that I need to write test case for:
const bookService = require('./bookService');
const libraryService = require('./libraryService');
const findBook = (bookName) => {
libraryService.getAllBooks().then(res => {
if(res.length > 0){
//find book code based on bookName in res....
bookCode = ...;
const url = bookService.getBookUrl(bookCode) + '/booksystem?bookcode=' + bookCode;
return new Promise((resolve, reject) => {
bookService.InfoRequest(bookCode, url, {}, 'GET', res => {
if(res.error){
reject(res);
}else{
//Do things here...
resolve(res)
}
})
})
}
})
}
I have tried stub the bookService.InfoRequest method, but it keeps giving me 1 uncaught exception says :
SyntaxError: The URL '/booksystem?bookcode=' is invalid..
I try to console log the url in the code, it prints out ok. But unit test case giving me uncaught exception.
I am using Ava, so I tried something like this:
test('find Book positive test', t => {
sandbox.stub(libraryService, 'getAllBooks').resolves([
{Name : 'book1', Code : 'b1'},
{Name : 'book2', Code : 'b2'},
{Name : 'book3', Code : 'b3'}
]);
const testRes = [
{bookCode: 'b1', price : 10},
{bookCode: 'b2', price : 20},
{bookCode: 'b3', price : 30}
];
const stubBookService = sandbox.stub(bookService, 'InfoRequest');
stubBookService.callsFake((bookCode, url, {}, method, callback) => {
callback(testRes);
})
api.findBook('book1');
})
api is the module that I am testing. Also in this case, what is the best way to assert? Thank you