Skip to content

Commit edca3cf

Browse files
author
Kristján Oddsson
authored
Add section on applying plugin multiple times
1 parent bbed94f commit edca3cf

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

_guides/index.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,36 @@ export default function myPlugin(chai, utils) {
6767
}
6868
```
6969

70+
### Guard against multiple calls to `use(..)`
71+
72+
In certain situations the `use(..)` function could be called multiple times with your plugin. For a lot of plugins this won't be a issue but it's considered best practise to check if the plugin has been applied already.
73+
74+
Here's a contrived example of how you might implement a check in your plugin but the actual implementation is left up to the plugin author.
75+
76+
```js
77+
import * as chai from 'chai';
78+
79+
let overwritten = false;
80+
81+
function somePlugin(base) {
82+
if (!overwritten) {
83+
base.util.overwriteMethod(base.Assertion.prototype, "equal", function (_super) {
84+
return function(...args) {
85+
console.log("Called!"); // log something out
86+
87+
return _super.call(this, ...args);
88+
};
89+
});
90+
overwritten = true;
91+
}
92+
}
93+
94+
chai.use(somePlugin);
95+
chai.use(somePlugin);
96+
97+
chai.expect(123).to.equal(123); // Logs `Called!` only once
98+
```
99+
70100
By following these guidelines, you can create Chai plugins that are easy to use and maintain.
71101

72102
- [Core Plugin Concepts]({{site.github.url}}/guide/plugins/) covers the basics of using the Chai Plugin API.

0 commit comments

Comments
 (0)