How to write tests for a library that requires being run on the browser (like Dexie.js or localforage)?

twitter logo ・1 min read

I've been trying to take a TDD approach to building up a side project using mocha and chai, but I've been hitting a wall lately. I want to use localforage, but I can't seem to write automated tests that run and interact with localforage since it requires being run on a browser. I want to wrap a library and write tests to cover the class that I created. Is there a way to do this?

twitter logo DISCUSS (6)
markdown guide
 

You can always mock those dependencies since those libraries should have been in theory tested before so you only need to test your logic. There's a lot of different ways you can do this, for example in Jest you can simply do in the top of your test:

jest.mock('localforage')

And it'll automatically mock every import that your code does of localforage so that instead of running the real library you can just mock the calls. You can read more here: jestjs.io/docs/en/mock-functions

I suppose Mocha has a similar approach too if you want to use it.

 

If you need DOM access, some testing libraries like Jest provide a sort of pseudo-DOM that you can interact with and mock out the parts that aren't provided.

There is also JSDOM which is a Node implementation of the DOM that you could use with testing tools like Mocha/Chai that don't have built-in DOM support.

If you want full browser automation then you'll need an E2E testing tool. For that there's tools Puppeteer, Cypress.io. I don't recommend Selenium.

 

I'll look into Jest & check those E2E tools out! Thanks!

 

Karma is a test runner that execute tests in a browser. It supports mocha and chai.

karma-runner.github.io/latest/inde...

I recommend to use mocks if you can but this tool can help if you can't or want to do e2e tests

 

Have you tried mocking local storage? Mock-Local-Storage looks like the package you need.

 
Classic DEV Post from Dec 10 '18

Is Jira an antipattern?

A look at an article about Jira and devs via Techcrunch

Corey Johnson profile image
Android developer interested in ethical user experiences and education software