gpt4 book ai didi

node.js - 使用 Jasmine 测试 Nodejs 中的事件

转载 作者:太空宇宙 更新时间:2023-11-04 00:11:35 27 4
gpt4 key购买 nike

我有嵌入式 C 背景,对 Node.js 或面向对象编程的东西不太熟悉。
我编写了一个示例 node.js 应用程序,用于在控制台上打印 Hello WorldBye Bye World 并使用事件发射器在两个打印上发出事件.

我有以下目录结构:

TestScripts/  
├── helloworld.js
├── index.js
├── node_modules
│   └── jasmine
├── package.json
└── spec
├── support
└── TddHelloWorld_spec.js

helloworld.js

var events = require('events');
var util = require('util');

var SayHello = function() {
var self = this;

SayHello.prototype.hello = function(){
console.log("Hello World");
if (self.emit) self.emit("SendingHelloToWorld");
}
SayHello.prototype.bye = function(){
console.log("Bye Bye Cruel World!!");
if (self.emit) self.emit("SendingByeByeToWorld");
}
}

util.inherits(SayHello, events.EventEmitter);
module.exports = SayHello;

index.js

var HelloWorld = require('./helloworld.js');

var HelloWorldInstance = new HelloWorld();


HelloWorldInstance.on("SendingByeByeToWorld", function(){
console.log("Got Bye Event");
});

HelloWorldInstance.on("SendingHelloToWorld", function(){
console.log("Got Hello Event");
});
HelloWorldInstance.hello();
HelloWorldInstance.bye();

TddHelloWorld_spec.js

describe('Call Hello World', function() {
var HelloWorld = require('../helloworld.js');
var HelloWorldInstance = new HelloWorld();


beforeEach(function(done) {
done();
});
afterEach(function(done) {
done();
});

it('should initialize WiFi via Connman', function(done) {
HelloWorldInstance.hello();
done();
});

it('should Call bye bye function', function(done) {
HelloWorldInstance.bye();
done();
});
it('should listen for Event', function() {
HelloWorldInstance.on("SendingHelloToWorld", function() {
console.log("Hit Event");
});
});

it('should listen for Event', function() {
HelloWorldInstance.on("SendingByeByeToWorld", function() {
console.log("Hit Bye Bye Event");
});
});
});

package.json

{
"name": "testscripts",
"version": "1.0.0",
"description": "Sample Project for Testing",
"main": "index.js",
"dependencies": {
"jasmine": "^3.1.0"
},
"devDependencies": {},
"scripts": {
"test": "jasmine",
"start": "node index.js"
},
"author": "",
"license": "ISC"
}

我面临的问题是,当我使用 npm test 运行测试时,测试用例以相反的顺序执行,并且不能保证事件处理的测试用例的执行。
如果我再次执行 npm test ,那么事件处理的测试用例可能会被执行,但它不会在每次运行时都执行。
有时事件处理的测试用例会被执行,有时则不会。

另外,请告诉我我是否以正确的方式使用 jasmine 测试事件?

这就是我获取测试输出的方式:
TDDExec

最佳答案

将您的测试稍微捆绑在一起。首先附加一个事件监听器,这是测试,然后调用例如.hello() 来触发它。

describe('Call Hello World', function() {
var HelloWorld = require('../helloworld.js');
var HelloWorldInstance = new HelloWorld();

it('should emit SendingHelloToWorld', function(done) {
HelloWorldInstance.on("SendingHelloToWorld", function() {
console.log("Hit Event");
done();
});
HelloWorldInstance.hello();
});
});

关于node.js - 使用 Jasmine 测试 Nodejs 中的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49254117/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com