Test the Hidden Promise Using Done or Await
Understand how to test methods that do not expose the Promise, using either the Done function or async and await.
In everyday work, we often need to deal with Promises (MDN article). If the function we test is async
(it returns a Promise
), we can use async
and await
in our tests.
When the function is not returning a Promise
and not using the async
keyword but still relies on a Promise
, we can’t use Jasmine’s asynchronous testing capabilities directly. There are two approaches for testing such functions/methods that hide their instances of Promise
:
- The Done function from Jasmine.
- The async and await keywords with an assisting Promise.
Let’s start with the class that has this hidden Promise
method: - the ArticleDelete class
.
The hidden Promise
What follows is a very simplified example of a class that handles deleting articles in a browser application. It accepts some input and makes a request to a server API if conditions are met.
For this lesson, the
delete
method is not asynchronous, but it still uses thePromise
returningArticleAPI
and works with.then
and.catch
callbacks (click for information on Promise chain flow). ThePromise
is not exposed; so, it’s hidden.
Run the code playground below and see the breakdown below.
const specReporter = require('jasmine-spec-reporter').SpecReporter module.exports = { srcDir: "src", srcFiles: [ "**/*.?(m)js" ], specDir: "spec", specFiles: [ "**/*[sS]pec.?(m)js" ], helpers: [ "helpers/**/*.?(m)js" ], random: false, stopSpecOnExpectationFailure: false, browser: { name: "headlessChrome" }, reporters: [new specReporter()] }
ArticleDelete
class breakdown
The ArticleDelete
class is relying on an ArticleAPI
class to make a DELETE /api/article/:id` call if conditions are met.
-
ArticleAPI
is a class that would implement the server API call. It’s empty because that’s outside of the current lesson’s scope, and we’ll be mocking its responses for the tests. -
ArticleDelete
is the main class.-
import { ArticleAPI } from './article-api.mjs';
This line imports the
ArticleAPI
dependency from the adjacent module in the current folderarticle-api.mjs
. -
export class ArticleDelete {
This line exports the class for use in other modules. ...
-
/** @type {ArticleAPI} */ articleAPI; deleteResult; /** * @param { ArticleAPI } article the article api */ constructor(articleApi) {
-