简体   繁体   中英

How to test a function inside a default function of a Worker in Jest?

I have a Javascript file, sortWorker.js , of the following format:

export default () => {

    function sortData (data) {
        //some computation here

        return sortedData
    }

    self.addEventListener ("message", e => {
        postMessage(sortData(e.data))
    })
}

I am trying to test the sortData() function in isolation in Jest, but I am struggling to achieve this. Since this is a worker file, I cannot move sortData outside the export default scope. Could someone please help me with this? Thanks!

Try to return your function so you can call it right inside your test:

export default () => {

    const sortData = function (data) {
        //some computation here

        return sortedData
    }

    self.addEventListener ("message", e => {
        postMessage(sortData(e.data))
    })

    return { sortData };
}

So in your test you can call sortData(data) and assert its results.


EDIT: the OP asked to involve it in a sctruture. You could make something like:

sort.js

export default () => {

  const sortData = function (data) {
    return data.sort();
  }

  return { sortData };
}

sort.test.js

import sort from './sort';

const sortFn = sort().sortData;

const resp = sortFn([4, 3, 2, 1]);

console.log(resp); // [1, 2, 3, 4]

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