最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

node.js中的笑话测试失败,显示匹配器错误

IT培训 admin 2浏览 0评论

node.js中的笑话测试失败,显示匹配器错误

笑话测试失败。匹配器错误:接收到的值必须具有length属性,其值必须为数字

Received has type:  object
Received has value: {}

但是对象有一个值,但不是{}

index.js文件

const fs = require('fs');

select('company')

async function select(selector)   {

await fs.readFile('./content.html', 'utf8',    function (err, data) {
 if (err) throw err;

 regexForIds = new RegExp(/<([^\s]+).*?id="company".*?>(.+?)<\/\1>/gi);

 matches = data.match(regexForIds);

 const obj = {
   length:  matches.length
 };

 return obj

});

}

module.exports = select;

index.js文件

const select = require('./');
test('select supports ids', () => {
  expect(select('#company')).toHaveLength(1);
});
回答如下:
  • [fs.readFile不返回承诺,因此await fs.readFile无效。
  • [select是一个异步函数,它不返回obj,所以expect(select('#company')).toHaveLength(1)也不起作用。

您可以通过用一个Promise包裹fs.readFile来解决第一点(请注意,还有其他解决方法,例如使用promisify):

const fs = require("fs"); async function select(selector) { const obj = await new Promise((res, rej) => { fs.readFile("./content.html", "utf8", function(err, data) { if (err) rej(err); regexForIds = new RegExp(/<([^\s]+).*?id="company".*?>(.+?)<\/\1>/gi); matches = data.match(regexForIds); const obj = { length: matches.length, }; res(obj); }); }); return obj; } module.exports = select;

要修正第二点,您需要稍稍更改测试,方法是在调用await之前添加select

const select = require("./"); test("select supports ids", async () => { expect(await select("#company")).toHaveLength(1); });

您可能必须根据运行测试的方式来更改./content.html的位置。

node.js中的笑话测试失败,显示匹配器错误

笑话测试失败。匹配器错误:接收到的值必须具有length属性,其值必须为数字

Received has type:  object
Received has value: {}

但是对象有一个值,但不是{}

index.js文件

const fs = require('fs');

select('company')

async function select(selector)   {

await fs.readFile('./content.html', 'utf8',    function (err, data) {
 if (err) throw err;

 regexForIds = new RegExp(/<([^\s]+).*?id="company".*?>(.+?)<\/\1>/gi);

 matches = data.match(regexForIds);

 const obj = {
   length:  matches.length
 };

 return obj

});

}

module.exports = select;

index.js文件

const select = require('./');
test('select supports ids', () => {
  expect(select('#company')).toHaveLength(1);
});
回答如下:
  • [fs.readFile不返回承诺,因此await fs.readFile无效。
  • [select是一个异步函数,它不返回obj,所以expect(select('#company')).toHaveLength(1)也不起作用。

您可以通过用一个Promise包裹fs.readFile来解决第一点(请注意,还有其他解决方法,例如使用promisify):

const fs = require("fs"); async function select(selector) { const obj = await new Promise((res, rej) => { fs.readFile("./content.html", "utf8", function(err, data) { if (err) rej(err); regexForIds = new RegExp(/<([^\s]+).*?id="company".*?>(.+?)<\/\1>/gi); matches = data.match(regexForIds); const obj = { length: matches.length, }; res(obj); }); }); return obj; } module.exports = select;

要修正第二点,您需要稍稍更改测试,方法是在调用await之前添加select

const select = require("./"); test("select supports ids", async () => { expect(await select("#company")).toHaveLength(1); });

您可能必须根据运行测试的方式来更改./content.html的位置。
发布评论

评论列表 (0)

  1. 暂无评论