1

我有一个测试来测试我的 cloudflare 工作者,如下所示:

const workerScript = fs.readFileSync(
    path.resolve(__dirname, '../pkg-prd/worker.js'),
    'utf8'
);

describe('worker unit test', function () {
    // this.timeout(60000);
    let worker;

    beforeEach(() => {
        worker = new Cloudworker(workerScript, {
            bindings: {
                HTMLRewriter
            },
        });
    });

    it('tests requests and responses', async () => {
        const request = new Cloudworker.Request('https://www.example.com/pathname')
        const response = await worker.dispatch(request);
        console.log(response);
        // const body = await response.json();
        expect(response.status).to.eql(200);
        // expect(body).to.eql({message: 'Hello mocha!'});
    });
});

在我的工人中,我做这样的事情:

 const response = await fetch(BASE_URL, request);
        const modifiedResponse = new Response(response.body, response);

        // Remove the webflow badge
        class ElementHandler {
            element(element) {
                element.append('<style type="text/css">body .w-webflow-badge {display: none!important}</style>', {html: true})
            }
        }
        console.log(3);

        return new HTMLRewriter()
            .on('head', new ElementHandler()).transform(modifiedResponse);

现在,当我运行测试时,我收到以下错误消息:

  ● worker unit test › tests requests and responses

TypeError: Cannot read property 'transform' of undefined

  at evalmachine.<anonymous>:1:1364
  at FetchEvent.respondWith (node_modules/@dollarshaveclub/cloudworker/lib/cloudworker.js:39:17)

似乎有什么问题?

我创建的 HTMLRewriter 如下所示:

function HTMLRewriter() {
    const elementHandler = {};

    const on = (selector, handler) => {
        if (handler && handler.element) {
            if (!elementHandler[selector]) {
                elementHandler[selector] = [];
            }
            elementHandler[selector].push(handler.element.bind(handler));
        }
    };

    const transform = async response => {
        const tempResponse = response.clone();

        const doc = HTMLParser.parse(await tempResponse.text());
        Object.keys(elementHandler).forEach(selector => {
            const el = doc.querySelector(selector);
            if (el) {
                elementHandler[selector].map(callback => {
                    callback(new _Element(el));
                });
            }
        });

        return new Response(doc.toString(), response);
    };

    return {
        on,
        transform
    };
}
4

1 回答 1

1

由于HTMLRewriter()使用 调用new,因此该函数需要是构造函数。在 JavaScript 中,构造函数应该设置属性this并且不应该返回值。但是,您的函数被编写为返回一个值。

所以,试着改变这个:

return {
    on,
    transform
};

对此:

this.on = on;
this.transform = transform;
于 2020-09-16T17:26:53.410 回答