如何在Node.js中测试流的错误?

时间:2018-10-18 06:05:59

标签: javascript node.js typescript jestjs

我有一个创建md5的函数,并且创建了一个测试以检查其行为,该脚本有效。现在,我需要创建一个测试,以检查createHash()createReadStream()失败时诺言是否被拒绝。 如何测试这种情况下的最佳实践?如果您能发表样品,我将不胜感激!

export const md5 = (path: string) =>
  new Promise<string>((resolve, reject) => {
    const hash = createHash("md5");
    const rs = createReadStream(path);
    rs.on("error", reject);
    rs.on("data", chunk => hash.update(chunk));
    rs.on("end", () => resolve(hash.digest("hex")));
  });

describe("md5", () => {
  const fileName = `${TEST_DIR}/file1.txt`;

  beforeAll(() => createFile(fileName));

  afterAll(() => removeFile(TEST_DIR));

  it("should hash md5 a file", () => {
    md5(fileName).then((hash: string) => {
      assert.strictEqual(hash, "4738e449ab0ae7c25505aab6e88750da");
    });
  });
});

2 个答案:

答案 0 :(得分:0)

  

我需要创建一个测试来检查诺言是否被拒绝

尝试下面的代码:茉莉花it块的第二个参数是一个传递了参数done的函数。 done是用户可以调用以使测试通过的功能。如果未在超时窗口内调用done,则Jasmine会将测试视为失败

stream-reader.js

const fs = require('fs')

const createReader = inputFile => {
  const reader = fs.createReadStream(inputFile, {encoding: 'utf8'})
  const result = new Promise((resolve, reject) => {
    reader.on('error', e => reject(e))
  })

  // return 2 things...
  return {
    reader,  // ...a stream that broadcasts chunks over time
    result,  // ...a Promise to be resolved on reading is done or error encountered
  }
}

module.exports = createReader

spec.js

const streamReader = require('../stream-reader')
const INPUT_FILE = './input1.txt'

describe('streamReader', () => {
    it(`should pass a chunk of the file on 'data' event`, (done) => {
        const api = streamReader(INPUT_FILE)
        api.reader.on('data', (chunk) => {
            console.log('[JASMINE TEST 1] received', chunk)
            done()
        })
    })

    /* test Promise.reject on stream error */
    it(`should reject on case of reading errors`, (done) => {
        const api = streamReader('./non/existent/file')
        api.result.catch(e => {
            console.log('[JASMINE TEST 2] correctly rejected')
            done()
        })
    })
})

输出

$ npm test

> so-jasmine-test@1.0.0 test C:\Users\jonathanlopez\nodejs\so-stream-reject
> jasmine

Randomized with seed 22758
Started
[JASMINE TEST 1] received the quick brown fox
.[JASMINE TEST 2] correctly rejected
.


2 specs, 0 failures
Finished in 0.026 seconds
Randomized with seed 22758 (jasmine --random=true --seed=22758)

希望这会有所帮助。 干杯。

答案 1 :(得分:0)

您可以通过这种方式使md5函数出错

        var names = [String]()
        var txts = [String]()
        var imgUrls = [String]()

Database.database().reference().child("Posts").child("dummy").observe(.value) { (snapshot) in
                guard let snapshots = snapshot.children.allObjects as? [DataSnapshot] else {
                    return
                }
                for snap in snapshots {
                    let autoId = snap.key as String
                    Database.database().reference().child("Posts").child("dummy").child(autoId).observe(.value, with: { (snapshot) in
                        guard let data = snapshot.value as? [String: Any] else {return}

                        //name
                        guard let name =  data["name"] as? String else {return}
                        self.names.append(name)
                        //image
                        guard let imgUrl = data["image"] as? String else {return}
                        self.imgUrls.append(imgUrl)
                        //txt
                        guard let txt = data["text"] as? String else {return}
                        self.txts.append(txt)

                        print(self.names) //this returns all data from firebase
                        print(self.imgUrls) //this returns all data from firebase
                        print(self.txts) //this returns all data from firebase
      }
                        print(self.names) //this returns empty array
                        print(self.imgUrls) //this returns empty array
                        print(self.txts) //this returns empty array
    }