簡體   English   中英

為什么 JSON.parse 在異步單元測試中導致問題,但在控制台中卻沒有?

[英]Why is JSON.parse causing problems in an async unit test, but not in the console?

語境

我正在嘗試通過無服務器堆棧示例進行測試,並且目前正在對此處給出的 create.js 文件進行單元測試。

問題

它目前是一個沒有斷言的簡單測試,但是當它達到JSON.parse(event.body)時,它會Unexpected token u in JSON at position 0

創建.test.js

import * as create from '../create.js';

test('create', async () => {
  const event = JSON.stringify({'body': 'event'}); // alternatively '{ "body": "test" }';
  const context = 'context';
  const callback = (error, response) => {
    expect(response.statusCode).toEqual(200);
  };

  await create.main(event, context, callback);
});

創建.js

import * as uuid from "uuid";
import AWS from "aws-sdk";

const dynamoDb = new AWS.DynamoDB.DocumentClient();

export async function main(event, context) {
  // Request body is passed in as a JSON encoded string in 'event.body'
  const data = JSON.parse(event.body);

  const params = {
    TableName: process.env.tableName,
    Item: {
      // The attributes of the item to be created
      userId: "123", // The id of the author
      noteId: uuid.v1(), // A unique uuid
      content: data.content, // Parsed from request body
      attachment: data.attachment, // Parsed from request body
      createdAt: Date.now(), // Current Unix timestamp
    },
  };

  try {
    await dynamoDb.put(params).promise();

    return {
      statusCode: 200,
      body: JSON.stringify(params.Item),
    };
  } catch (e) {
    return {
      statusCode: 500,
      body: JSON.stringify({ error: e.message }),
    };
  }
}

我嘗試在控制台中刪除 JSON.parse,它有效,並且我嘗試在控制台中運行JSON.parse(JSON.stringify({'body': 'event'})) ,這也有效。

問題

如何修復我的測試,以便JSON.parse(event.body)不會引發錯誤?

當給JSON.parse的值實際上是undefined時,通常會看到該錯誤。 所以,我會檢查試圖解析這個的代碼——很可能你沒有解析。 它也可能是“未定義”作為字符串而不是文字未定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM