Challenges when Testing Plugins
Testing a plugin, which is intended to run in a very specific environment - Obsidian - can be quite challenging. If you ever tried to test an Obsidian plugin you probably noticed that testing a file that imports something from the Obsidian API causes the test runner to fail. This is because the Obsidian package only provides TypeScript types but no actual JavaScript code for said types. The code is only available inside of Obsidian, but not in our test runner of choice. There are a few options around this though.
Mocking the Obsidian API
Section titled “Mocking the Obsidian API”Of course, you can go ahead and mock the entirety of the Obsidian API, but that has its own set of problems. The major ones are
- the mocks are a lot of work to write
- you have to maintain and update them when the Obsidian API changes
- you are only testing against how you think the Obsidian API works and some of those assumptions can be false, leading to your tests passing but your plugin still being buggy
If you want to go down this route, you might have some success with projects like this: https://github.com/mnaoumov/obsidian-test-mocks
Using Dependency Injection and Interfaces
Section titled “Using Dependency Injection and Interfaces”This video explains the idea behind this approach quite well.
https://www.youtube.com/watch?v=J1f5b4vcxCQ
This pattern allows for simply swapping out the adapters of the parts that you don’t want to test for bare bones versions.