繁体   English   中英

TypeError [ERR_INVALID_ARG_TYPE]:“路径”参数必须是字符串类型。 收到 Object 的实例

[英]TypeError [ERR_INVALID_ARG_TYPE]: The “path” argument must be of type string. Received an instance of Object

I am using the source code from a security rules tutorial to attempt to do integration testing with Jest for my Javascript async function async_create_post , used for my firebase HTTP function create_post The files involved has a directory structure of the following:

测试文件: root/tests/handlers/posts.test.js

要测试的文件: root/functions/handlers/posts.js

教程中的帮助代码: root/tests/rules/helpers.js

这是涉及的源代码:

post.test.js

const { setup, teardown} = require("../rules/helpers");
const {
  async_get_all_undeleted_posts,
  async_get_post,
  async_delete_post,
  async_create_post
} = require("../../functions/handlers/posts");


describe("Post Creation", () => {
  afterEach(async () => {
    await teardown();
  });

  test("should create a post", async () => {

    const db = await setup();


    const malloryUID = "non-existent uid";
    const firstPost = {
      body: "First post from Mallory",
      author_id: malloryUID,
      images: ["url1", "url2"]
    }

    const before_post_snapshot = await db.collection("posts").get();
    expect(before_post_snapshot.docs.length).toBe(0);


    await async_create_post(firstPost); //fails at this point, expected to create a new post, but instead threw an error
    const after_post_snapshot = await db.collection("posts").get();
    expect(after_post_snapshot.docs.length).toBe(1);
  });

});

帖子.js

const {admin, db } = require('../util/admin');
//admin.initializeApp(config); //my credentials
//const db = admin.firestore();
const { uuid } = require("uuidv4");

const {
  success_response,
  error_response
} = require("../util/validators");


exports.async_create_post = async (data, context) => {

  try {    
    const images = [];
    data.images.forEach((url) => {
      images.push({
        uid: uuid(),
        url: url
      });
    })
    const postRecord = {
      body: data.body,
      images: images,
      last_updated: admin.firestore.FieldValue.serverTimestamp(),
      like_count: 0,
      comment_count: 0,
      deleted: false,
      author_id: data.author_id
    };

    const generatedToken = uuid();

    await db
      .collection("posts")
      .doc(generatedToken)
      .set(postRecord);

    // return success_response();
    return success_response(generatedToken);
  } catch (error) {
    console.log("Error in creation of post", error);
    return error_response(error);
  }
}

当我在 Webstorm IDE 中运行测试时,1 个终端运行Firebase emulators:start ,我收到以下错误消息。

console.log
    Error in creation of post TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received an instance of Object
        at validateString (internal/validators.js:120:11)
        at Object.basename (path.js:1156:5)
        at GrpcClient.loadProto (/Users/isaac/Desktop/project/functions/node_modules/google-gax/src/grpc.ts:166:23)
        at new FirestoreClient (/Users/isaac/Desktop/project/functions/node_modules/@google-cloud/firestore/build/src/v1/firestore_client.js:118:38)
        at ClientPool.clientFactory (/Users/isaac/Desktop/project/functions/node_modules/@google-cloud/firestore/build/src/index.js:330:26)
        at ClientPool.acquire (/Users/isaac/Desktop/project/functions/node_modules/@google-cloud/firestore/build/src/pool.js:87:35)
        at ClientPool.run (/Users/isaac/Desktop/project/functions/node_modules/@google-cloud/firestore/build/src/pool.js:164:29)
        at Firestore.request (/Users/isaac/Desktop/project/functions/node_modules/@google-cloud/firestore/build/src/index.js:961:33)
        at WriteBatch.commit_ (/Users/isaac/Desktop/project/functions/node_modules/@google-cloud/firestore/build/src/write-batch.js:485:48)
        at exports.async_create_post (/Users/isaac/Desktop/project/functions/handlers/posts.js:36:5) {
      code: 'ERR_INVALID_ARG_TYPE'
    }

      at exports.async_create_post (/Users/isaac/Desktop/project/functions/handlers/posts.js:44:13)


Error: expect(received).toBe(expected) // Object.is equality

Expected: 1
Received: 0
<Click to see difference>


    at Object.<anonymous> (/Users/isaac/Desktop/project/tests/handlers/posts.test.js:59:45)

Error in creation of post来自console.log("Error in creation of post", error); posts.js中,所以错误显示在这篇文章的标题中。

我想知道为什么从posts.test.js async_create_post导致这个错误,并且不会像预期的行为那样用额外的记录填充我的数据库。 如果需要更多信息来解决问题,请通知我。

以下是一些可能提供更多上下文的代码片段。

helpers.js [从存储库复制]

const firebase = require("@firebase/testing");
const fs = require("fs");

module.exports.setup = async (auth, data) => {
  const projectId = `rules-spec-${Date.now()}`;

  const app = firebase.initializeTestApp({
    projectId,
    auth
  });

  const db = app.firestore();

  // Apply the test rules so we can write documents
  await firebase.loadFirestoreRules({
    projectId,
    rules: fs.readFileSync("firestore-test.rules", "utf8")
  });

  // write mock documents if any
  if (data) {
    for (const key in data) {
      const ref = db.doc(key); // This means the key should point directly to a document
      await ref.set(data[key]);
    }
  }

  // Apply the actual rules for the project
  await firebase.loadFirestoreRules({
    projectId,
    rules: fs.readFileSync("firestore.rules", "utf8")
  });

  return db;
  // return firebase;
};

module.exports.teardown = async () => {
  // Delete all apps currently running in the firebase simulated environment
  Promise.all(firebase.apps().map(app => app.delete()));
};

// Add extensions onto the expect method
expect.extend({
  async toAllow(testPromise) {
    let pass = false;
    try {
      await firebase.assertSucceeds(testPromise);
      pass = true;
    } catch (error) {
      // log error to see which rules caused the test to fail
      console.log(error);
    }

    return {
      pass,
      message: () =>
        "Expected Firebase operation to be allowed, but it was denied"
    };
  }
});

expect.extend({
  async toDeny(testPromise) {
    let pass = false;
    try {
      await firebase.assertFails(testPromise);
      pass = true;
    } catch (error) {
      // log error to see which rules caused the test to fail
      console.log(error);
    }

    return {
      pass,
      message: () =>
        "Expected Firebase operation to be denied, but it was allowed"
    };
  }
});

index.js

const functions = require('firebase-functions');


const {
  async_get_all_undeleted_posts,
  async_get_post,
  async_delete_post,
  async_create_post
} = require('./handlers/posts');



exports.create_post = functions.https.onCall(async_create_post);

错误消息意味着path模块的方法(如path.join )期望其 arguments 之一是字符串,但得到了其他内容。

我通过二进制搜索对程序进行注释找到了有问题的行,直到错误消失。

也许您的一个模块使用path并且您提供了错误的 arguments。

暂无
暂无

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

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