1

该函数从 JSON 文件中读取数据并将其打印出来。它不应该在课堂上。如果被调用,我很难测试它。

function load(nameString) {
  nameString = nameString.toLowerCase().split(" ");
  const fs = require("fs");
  fs.readFile(
    `visitor_${nameString[0]}_${nameString[1]}.json`,
    "utf8",
    (err, visitorInfo) => {
      if (err) {
        console.log("Error reading file from disk:", err);
        return;
      }
      try {
        console.log(JSON.parse(visitorInfo));
      } catch {
        console.log("Error parsing visitor info", err);
      }
    }
  );
}
4

1 回答 1

1

对于"jasmine": "^3.6.3",您可以使用spyOn(obj, methodName)将间谍安装到fs.readFile()方法上。用于callFake(fn)告诉间谍在调用时调用假实现。我们可以在有错误或正常值的测试用例中获取和调用callbackof 。fs.readFile()

load.js

function load(nameString) {
  nameString = nameString.toLowerCase().split(' ');
  const fs = require('fs');
  fs.readFile(`visitor_${nameString[0]}_${nameString[1]}.json`, 'utf8', (err, visitorInfo) => {
    if (err) {
      console.log('Error reading file from disk:', err);
      return;
    }
    try {
      console.log(JSON.parse(visitorInfo));
    } catch {
      console.log('Error parsing visitor info', err);
    }
  });
}

module.exports = load;

load.test.js

const fs = require('fs');
const load = require('./load');

describe('69014390', () => {
  it('should read file', () => {
    spyOn(fs, 'readFile').and.callFake((path, options, callback) => {
      callback(null, JSON.stringify({ name: 'teresa teng' }));
    });
    spyOn(console, 'log');
    load('teresa teng');
    expect(fs.readFile).toHaveBeenCalledWith('visitor_teresa_teng.json', 'utf8', jasmine.any(Function));
    expect(console.log).toHaveBeenCalledWith({ name: 'teresa teng' });
  });

  it('should handle error', () => {
    const error = new Error('ENOENT');
    spyOn(fs, 'readFile').and.callFake((path, options, callback) => {
      callback(error);
    });
    spyOn(console, 'log');
    load('teresa teng');
    expect(fs.readFile).toHaveBeenCalledWith('visitor_teresa_teng.json', 'utf8', jasmine.any(Function));
    expect(console.log).toHaveBeenCalledWith('Error reading file from disk:', error);
  });
});

测试结果:

Executing 2 defined specs...
Running in random order... (seed: 74926)

Test Suites & Specs:

1. 69014390
   ✔ should read file (6ms)
   ✔ should handle error (1ms)

>> Done!


Summary:

  Passed
Suites:  1 of 1
Specs:   2 of 2
Expects: 4 (0 failures)
Finished in 0.019 seconds
于 2021-09-02T04:57:21.220 回答