我如何用玩笑测试异步获取功能

时间:2021-08-01 10:09:41

标签: javascript jestjs fetch

谁能告诉我我是如何用jest测试这个功能的

export function handleSubmitTest() {

  const postData = async ( url = '', data = {})=>{
        const response = await fetch(url, {
        method: 'POST', 
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json',
        },
       // Body data type must match "Content-Type" header        
        body: JSON.stringify(data), 
      });
  
        try {
          const newData = await response.json();
          console.log(newData);
          return newData;
        }catch(error) {
        console.log("error", error);
        }
    }
    return postData('http://localhost:8081/analyze', {text: "Picard"});
}

这是我在测试文件中所做的,但是当我在命令行中运行测试时,它给了我未定义 fetch 的错误。

import { handleSubmitTest } from '../formHandler'
import 'regenerator-runtime/runtime';



test('55555', async () => {

    const data = await handleSubmitTest()

    expect(data).toBe({text: "Picard"});

  });

2 个答案:

答案 0 :(得分:1)

fetchwindow 范围内定义。 JSDom,Jest 使用的 DOM 实现在范围内没有该属性。您需要 create a mock of the property you need 才能运行测试。

话虽如此……如果您正在测试模拟,那么您真正在测试什么?

即您可能想要测试正在创建或使用此 JSON 而非原生 JavaScript 功能的代码。

答案 1 :(得分:-1)

为此需要编写模拟 API。