DEV Community

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

Corey Johnson on May 03, 2019

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 loca...
Collapse
 
sleepyfran profile image
Fran González

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.

Collapse
 
evanplaice profile image
Evan Plaice

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.

Collapse
 
johnson_cor profile image
Corey Johnson

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

Collapse
 
hugueschabot profile image
Hugues Chabot

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

Collapse
 
mykeels profile image
Backlog Slayer

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

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

Cypress is fantastic for this type of thing.

Collapse
 
jefrancomix profile image
Jesús Franco

But, it only works in Chrome