简体   繁体   中英

Jest unable to return value from jQuery

I need jest tests to fail if a jQuery selector returns 0. So if there is a typo, the test should fail.

Here's my index.js:

const sample = $('.someClass');
module.exports = sample;

This is how my index.test.js file looks like:

window.$ = window.jQuery = require('jquery');
const sample = require('./index');

 test('test for selector', () => {
   expect(sample.length).toBe(1);
 });

If I run a console.log(sample.length), it returns 1 on browser console but always 0 on jest. Can someone please help me with this?

For now I managed to go around the problem as follows:

const sampleClassName = '.someClass';
const sample = $(sampleClassName); // For later usage
module.exports = sampleClassName;

And in the test file:

window.$ = window.jQuery = require('jquery');
const sampleClassName = require('./index');

test('test for selector', () => {
  expect(someClassName).toBe('.someClass');
});

So this temporarily solves my problem but it would still be great to know if a better solution exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM