我有一个异步函数,它运行 2000 毫秒,然后它会抛出异常。我正在尝试使用 Mocha/chai 完全测试这种行为,但显然我做错了。
这就是我尝试过的:
第一的:
expect(publisher.dispatchMessage<ExampleResponseMessage>(message, {}, 2 * 1000)).to.eventually.throw();
Run Code Online (Sandbox Code Playgroud)
这将测试标记为通过(运行时间为 52 毫秒),但在 2 秒后抛出异常。所以显然它根本没有等待该功能的承诺。
第二:
expect(async () => {
await publisher.dispatchMessage<ExampleResponseMessage>(message, {}, 2 * 1000);
}).to.throw();
Run Code Online (Sandbox Code Playgroud)
测试失败:应在预定义超时后拒绝预定消息:AssertionError:预期 [Function] 在 Context.mocha_1.it (test\integration\rpc-communication.spec.ts:75:16) 处引发错误
预期行为是测试通过,因为在 2000 毫秒后抛出异常,这在给定的测试用例超时 4000 毫秒内。
附加信息:
这会奏效。承诺因错误而被拒绝(我也可以将其更改为用字符串拒绝)。这应该证明 dispatchMessage() 按预期工作。测试用例需要 2002 毫秒,然后通过。
try {
await publisher.dispatchMessage<ExampleResponseMessage>(message, {}, 2 * 1000);
} catch (err) {
expect(err).to.be.an('Error');
}
Run Code Online (Sandbox Code Playgroud)
题:
如何正确测试异步函数是否引发异常?
我们正在将一个非常大的项目移植到 Vue.js 中,并希望在我们进行时彻底实现我们的单元测试套件。
我们想验证组件是否在创建时设置了所有必需的属性,我的测试用例如下所示:
describe('Input', () => {
it('fail initialization with no value', () => {
const vm = mount(Input, {
propsData: {},
});
// expecting above to fail due to required prop 'value'
});
});
Run Code Online (Sandbox Code Playgroud)
该组件Input应包含一个属性value。我可以通过控制台发出的警告看到它丢失了,但我们希望在我们的单元测试中捕获它。直接测试这没有多大意义,但是一旦我们有组件嵌套多个组件,确保每个组件正确初始化其子组件很重要,这是通过向我们保证上述测试应该失败并被捕获失败来实现的。
然而,没有例外,我们有想法可以挂钩,Vue.warnHandler但这似乎只是确认构造函数按预期工作的大量工作。
是否有推荐的方法来使用 Vue.js 执行此操作?
有没有办法添加自定义方法来断言 chai 的接口?
我试过:
// test-helper.js
export const testPlugin = function(chai) {
chai.Assertion.addMethod('customMethod', function() {
//Something
})
}
// abc.test.js
import {assert, use} from 'chai'
import {testPlugin} from 'test-helper.js'
use(testPlugin)
Run Code Online (Sandbox Code Playgroud)
但我认为这只适用于 chai 的 expect 接口。我想使用这个自定义方法作为assert.customMethod(actual, expected)
如果我在这里遗漏了什么,请告诉我。
我有一项gulp任务负责使用mocha.
gulp.task('test', ['cls'], () => {
execout('mocha -r ts-node/register --timeout 999999 --colors test/*.test.ts');
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,如您所见,有些灰线很难看到:
我的问题是,我怎样才能改变这种颜色?
我成功地尝试了这里推荐的内容(它有效):
https : //github.com/mochajs/mocha/issues/802#issuecomment-18254298):
$ gulp test > >(perl -pe 's/\x1b\[90m/\x1b[92m/g') 2> >(perl -pe 's/\x1b\[90m/\x1b[92m/g' 1>&2)
Run Code Online (Sandbox Code Playgroud)
但我不喜欢那样,因为我不想每次运行该命令时都在命令行上写下所有内容。
然后我尝试将所有这些移动到gulp任务内部,如下所示:
gulp.task('test', ['cls'], () => {
execout("mocha -r ts-node/register --timeout 999999 --colors test/*.test.ts > >(perl -pe 's/\x1b\[90m/\x1b[92m/g') 2> >(perl -pe 's/\x1b\[90m/\x1b[92m/g' 1>&2)");
});
Run Code Online (Sandbox Code Playgroud)
但是后来我在终端上收到以下错误。
ERR: > was unexpected at this time.
Run Code Online (Sandbox Code Playgroud)
另一方面,这里还有另一个建议/方法,但我不知道如何使用它:
https://github.com/mochajs/mocha/issues/1200#issuecomment-62780003
关于如何修改难以阅读的灰线颜色的任何想法?
谢谢!
我对节点和表达很陌生。并且一直在尝试使用 mocha、chai 和 chai-http 编写测试代码。这是源代码的一部分。
const mongoose = require('mongoose'),
User = require('../../models/user');
const mongoUrl = 'mongodb://xxxxxxxxxxx';
describe('/test', function() {
before('connect', function() {
return mongoose.createConnection(mongoUrl);
});
beforeEach(async function(done) {
try {
await User.remove({}); // <-- This doesn't work
chai.request('http://localhost:3000')
.post('/api/test')
.send(something)
.end((err, res) => {
if (err) return done(err);
done();
});
} catch (error) {
done(error);
}
});
});
Run Code Online (Sandbox Code Playgroud)
我在“npm test”(nyc mocha --timeout 10000 test/**/*.js)中得到以下错误。
Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 Karma 作为我的测试运行器、Mocha 作为我的测试框架、Sinon 作为我的模拟/存根/间谍库和 Chai 作为我的断言库来对一个函数进行单元测试。我在 Karma 配置中使用 Chromium 作为我的无头浏览器。
但是,对于为什么我收到以下错误,我完全感到困惑:
TypeError: Cannot redefine property: assign
Run Code Online (Sandbox Code Playgroud)
...当我对此运行 npm test 时:
function routeToNewPlace() {
const newLoc = "/accountcenter/content/ac.html";
window.location.assign(newLoc);
}
describe('tests', function() {
before('blah', function() {
beforeEach('test1', function() {
window.onbeforeunload = () => '';
});
});
it('routeToNewPlace should route to new place', function() {
expectedPathname = "/accountcenter/content/ac.html";
routeToNewPlace();
const stub = sinon.stub(window.location, 'assign');
assert.equal(true, stub.withArgs(expectedUrl).calledOnce);
stub.restore();
});
});
Run Code Online (Sandbox Code Playgroud)
如您所见,我试图为 window.location 分配一个空字符串,但这似乎没有帮助。
这是我的 karma.config.js:
module.exports = function(config) {
config.set({
frameworks: ['mocha', …Run Code Online (Sandbox Code Playgroud) 我正在开发一个 NodeJS (v. 8.12.0, EcmaScript 6) 项目,其项目结构类似于:
project_root/
src/
utils/
protocol_messages/
helpers.js
tests/
unit/
utils/
protocol_messages/
helpers.js
Run Code Online (Sandbox Code Playgroud)
我正在使用 Mocha 作为测试框架编写测试。
问题
在helpers.jsunder 中tests/unit/utils/protocol_messages/,导入被测模块的正确方法是什么?
详细说明:
我想避免使用相对路径:require('../../../../../src/utils/protocol_messages/helpers')。
它有效,但很丑陋,如果项目结构发生变化,我也必须重写测试导入。
(我是 Javascript 的新手,所以我可能做错了几件事。)
更新此问题中
提供的解决方案:
require.main.require:在对此答案的评论中,“如果代码包含像 Mocha 测试这样的单元测试,则此解决方案将不起作用”。node_modules我src/的 NodeJS 项目的项目根目录下有一个额外的东西似乎没有意义。如果我在以上任何一点上有错误,请指出,因为我不知所措。在我看来,NodeJS 没有提供使用绝对路径导入 CommonJS 模块的本机方式。
我正在尝试为我的 nodejs 服务器应用程序编写测试,现在一切正常。我可以将我的代码从打字稿编译成 javascript 没有错误,但是当我尝试运行 mocha 测试时,打字稿预编译失败,因为在typings.d.ts.
这是我在里面的声明 typings.d.ts
import {User} from "./users/user.model";
import {MainDatabase} from "./core/models/database.model";
import {Translation} from "./core/services/i18n";
import {LanguageDefinition} from "./core/models/language.model";
import {Reminder} from "./core/services/schedule/schedule.model";
import {UserProfileModel} from "./core/database/models/user_profile";
import {UserClientModel} from "./core/database/models/user_client";
import {PhoneNumberModel} from "./core/database/models/phone_number";
import {CountryModel} from "./core/database/models/country";
import {CustomerTypeModel} from "./core/database/models/customer/customer_type";
import {CustomerModel} from "./core/database/models/customer/customer";
import {ReminderModel} from "./core/database/models/reminder_options";
import {Customer} from "./customers/customer.model";
import {IUserAccount} from "./core/database/models/user_account";
import {UserAccountModel} from "./core/database/models/user_account";
import {MailModel} from "./core/services/mail/mail.model";
import {Request} from "express";
import …Run Code Online (Sandbox Code Playgroud) JUnit 和 N/XUnit 都使我们能够参数化测试,这些测试仅因输入值和预期结果而异。换句话说,我们可以静态定义测试数据集(输入 + 预期结果),并让单个测试执行并验证每个输入集的结果。我们可以使用至少两个实用程序在 JS 中做同样的事情。
但是,对于 Java 和 .Net,我们可以进一步泛化测试,而不是测试特定值,我们可以使用理论(“@Theory”和“[Theory]”)描述生成输入数据的规则并动态生成测试数据分别)。
JS 中有什么实用程序可以在编写测试时实现这种抽象级别?
如果任何测试失败,我正在尝试配置 mocha 以重试整个套件。
我导航到一个 URL,然后填充一个表单并提交,然后用户被重定向,如果找到某个元素,则最后一次测试通过。
如果找不到该元素,我需要再次导航到表单,填写并提交,重新运行整个套件 N 次。
我已经在描述和它级别尝试过 this.retries() ,还有保释和重试标志,但 mocha 只重试失败的测试。
var count = 0
describe('Main suite', function () {
this.retries(5)
it('Some setup', () => {
console.log('1. Some setup');
});
it("bail issue", function() {
console.log('2. bail issue');
if (count < 4) {
count += 1
throw new Error("Must be retried")
}
})
});
describe('end', function () {
it('close', () => {
});
});
Run Code Online (Sandbox Code Playgroud)
mocha.js ×10
chai ×5
javascript ×4
node.js ×4
typescript ×4
testing ×2
unit-testing ×2
ecmascript-6 ×1
express ×1
karma-runner ×1
sinon ×1
tsconfig ×1
vue.js ×1