0

Hey everyone I made a package that can manage and control URL query strings. I publish it throw npm. and wrote some tests to the core of the package

"parser.js" - that parse the query string to an object

"strigifyer.js" - that make an object to URL query string

I test those files for now with "mocha" and "expect"

there is one main file that manage the above files and the file is also push to query string to URL without refresh. it uses the window.history object.

what should I do to success to test the main file (index.js)?

I need the window and history objects to check if there is a change after I use my api.

here is the package if its help: https://github.com/nevos12/query-string-manager

thank you.

1 Answer 1

1

If I understood correct, the module that exposes your library is src/index.js

From the code style of your index.js, I'd suggest to use sinon to test your code flow.

A unit test could be :

import sinon from 'sinon'
import qs from 'src/index.js'

it('should reset queryStringObject', () => {
  const pushToUrlSpy = sinon.spy(qs, 'pushToUrl');
  qs.reset(true);
  expect(qs.queryStringObject).to.equal({});
  expect(pushToUrlSpy.called);
  pushToUrlSpy.restore();
})

This code creates a spy on pushToUrl() , invokes reset() and asserts that queryStringObject is an empty object now and pushToUrl() was invoked as least once. In the end it restores the spy, otherwise other tests might act weird.

Sign up to request clarification or add additional context in comments.

5 Comments

nice, I think I get it, you are saying that with this library I can test all my "index.js" file but I cant actually test pushToUrl() method? I can just assert that it was called? (if yes it is fine, and maybe there is another way to test pushToUrl())
@Nevo You can test pushTourl() but you need to test one thing at a time and spy/stub/mock other parts. You can create another test for testing pushToUrl() and mock it's dependencies.
first - thanks for your answer, this is good enough for me. just to be clear, do you mean to mock the "window" object maybe? something like that?
@Nevo nope, I mean mock a method of the object you are willing to test. You can check out sinon documentation and understand them better.
Thank you I will try to understand it more

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.