简体   繁体   English

如何在Jest中的Worker的默认函数中测试函数?

[英]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: 我有一个Javascript文件sortWorker.js ,其格式如下:

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. 我正在尝试在Jest中sortData()测试sortData()函数,但是我正在努力实现这一点。 Since this is a worker file, I cannot move sortData outside the export default scope. 由于这是一个工作文件,因此无法将sortData移至export default范围之外。 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. 因此,在测试中,您可以调用sortData(data)并声明其结果。


EDIT: the OP asked to involve it in a sctruture. 编辑:OP要求将其包含在结构中。 You could make something like: 你可以做类似的事情:

sort.js sort.js

export default () => {

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

  return { sortData };
}

sort.test.js 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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