如何测试该提取响应是一种arraybuffer

发布于 2025-01-19 19:33:04 字数 2201 浏览 3 评论 0原文

我具有返回ArrayBuffer类型响应的函数,此功能正在获取.jpeg或.pdf数据,然后我使用它在浏览器中显示文档:

export async function getStatementsPDF(url: string, statement: Statement, setError: (err: any) => void) {
  return await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'include',
    body: JSON.stringify({
      reportNumber: statement.reportNumber,
      creationDate: statement.creationDate,
    }),
  })
    .then((response) => {
      if (response.ok) {
        return response.arrayBuffer();
      }
      throw new Error('Something goes wrong while fetching your statement!');
    })
    .catch((err) => setError(err));
}

现在,我尝试用Jest和jest and msw 我嘲笑了我的回复,现在在控制台中,我看到我的功能返回 ArrayBuffer,

import * as path from 'path';
import * as fs from 'fs';
import { setupServer } from 'msw/node';
import { getJointAccountsStatementsPDF } from '../index';
import { rest } from 'msw';

const URL = 'http://localhost:1234/testing';
const server = setupServer(
  rest.post(URL, (_, res, ctx) => {
    // Read the image from the file system using the "fs" module.
    const imageBuffer = fs.readFileSync(path.resolve(__dirname, './statement-demo.pdf'));
    return res(
      ctx.set('Content-Length', imageBuffer.byteLength.toString()),
      ctx.set('Content-Type', 'image/jpeg'),
      // Respond with the "ArrayBuffer".
      ctx.body(imageBuffer),
    );
  }),
);

describe('getStatementsPDF', () => {
  test.only('should return ArrayBuffer', async () => {
    server.listen();
    const res = await getStatementsPDF(
      URL,
      { creationDate: '2022-11-11', reportNumber: '21313', title: 'title' },
      (err) => {},
    );
    console.log('res', res);
    expect(res instanceof ArrayBuffer).toEqual(true);
  });
});

但这是:

expect(res instanceof ArrayBuffer).toEqual(true);

没有返回。

如何确保我的响应类型是ArrayBuffer?

I have a function that returns arrayBuffer type response, this function is fetching the .jpeg or .pdf data and then I use it to show document in the browser:

export async function getStatementsPDF(url: string, statement: Statement, setError: (err: any) => void) {
  return await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'include',
    body: JSON.stringify({
      reportNumber: statement.reportNumber,
      creationDate: statement.creationDate,
    }),
  })
    .then((response) => {
      if (response.ok) {
        return response.arrayBuffer();
      }
      throw new Error('Something goes wrong while fetching your statement!');
    })
    .catch((err) => setError(err));
}

now I try to test this function with jest and msw
I have mocked my response and now in the console I see that my function returns
ArrayBuffer

import * as path from 'path';
import * as fs from 'fs';
import { setupServer } from 'msw/node';
import { getJointAccountsStatementsPDF } from '../index';
import { rest } from 'msw';

const URL = 'http://localhost:1234/testing';
const server = setupServer(
  rest.post(URL, (_, res, ctx) => {
    // Read the image from the file system using the "fs" module.
    const imageBuffer = fs.readFileSync(path.resolve(__dirname, './statement-demo.pdf'));
    return res(
      ctx.set('Content-Length', imageBuffer.byteLength.toString()),
      ctx.set('Content-Type', 'image/jpeg'),
      // Respond with the "ArrayBuffer".
      ctx.body(imageBuffer),
    );
  }),
);

describe('getStatementsPDF', () => {
  test.only('should return ArrayBuffer', async () => {
    server.listen();
    const res = await getStatementsPDF(
      URL,
      { creationDate: '2022-11-11', reportNumber: '21313', title: 'title' },
      (err) => {},
    );
    console.log('res', res);
    expect(res instanceof ArrayBuffer).toEqual(true);
  });
});

But this:

expect(res instanceof ArrayBuffer).toEqual(true);

did not return true.

How can I make sure that my response type is ArrayBuffer?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏の忆 2025-01-26 19:33:04

您的getStatementPDF函数返回的承诺并不总是能通过arrayBuffer来实现。有时,它可以通过undefined(假设setError没有明确的返回带有值)。原因是:

.catch((err) => setError(err));

通过setError的返回值将拒绝转换为实现。

诺言最常见的错误之一是为时过早处理拒绝。 getStatementpdf几乎可以肯定不是处理拒绝,以便拒绝传播给呼叫者,这可以看到操作失败并相应地行动。

但是,如果您要拥有getStatementpdf执行此操作,那么您应该准备等待getStatementspdf有时会导致undefined

以下是a) 无法过早处理错误的函数的版本,b) 使用等待而不是明确的承诺回调函数:

export async function getStatementsPDF(url: string, statement: Statement) {
    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
            reportNumber: statement.reportNumber,
            creationDate: statement.creationDate,
        }),
    });
    if (response.ok) {
        throw new Error('Something goes wrong while fetching your statement!');
    }
    return await response.arrayBuffer();
    //     ^^^^^−−−−− this isn't strictly necessary, but it can make the `async`
    //                call stack clearer about where the error occurred
}

调用者在调用时会处理拒绝。您的测试可能不需要,因为我认为如果该功能拒绝其承诺,则测试应该失败。

The promise that your getStatementsPDF function returns doesn't always get fulfilled with an ArrayBuffer. Sometimes, it gets fulfilled with undefined (assuming setError doesn't have an explicit return with a value). The reason is this:

.catch((err) => setError(err));

That converts rejection into fulfillment with the return value of setError.

One of the most common mistakes with promises is handling rejection too early. getStatementsPDF should almost certainly not handle rejection, so that the rejection gets propagated to the caller, which can see that the operation failed and act accordingly.

But if you're going to have getStatementsPDF do that, then you should be prepared for await getStatementsPDF to sometimes result in undefined.

Here's a version of the function that A) Doesn't handle errors prematurely, and B) Uses await rather than explicit promise callback functions:

export async function getStatementsPDF(url: string, statement: Statement) {
    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
            reportNumber: statement.reportNumber,
            creationDate: statement.creationDate,
        }),
    });
    if (response.ok) {
        throw new Error('Something goes wrong while fetching your statement!');
    }
    return await response.arrayBuffer();
    //     ^^^^^−−−−− this isn't strictly necessary, but it can make the `async`
    //                call stack clearer about where the error occurred
}

The caller would handle rejection when calling it. Your test probably doesn't need to, because I assume the test should fail if the function rejects its promise.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文