【发布时间】:2018-06-28 08:21:04
【问题描述】:
我想在代码上使用异步功能进行单元测试。这是我在 user.test.js 上的代码
'use strict'
const UserDomain = require("../../../../../../bin/modules/users/repositories/commands/domain")
const UserHandler = require("../../../../../../bin/modules/users/repositories/commands/command_handler")
const expect = require('chai').expect;
const assert = require('chai').assert;
const sinon = require('sinon');
describe('User domain', () => {
describe('".login(data)"', () => {
let user;
beforeEach( () => {
user = {
clientId : "adithyavisnu",
clientSecret : "secretOfmine@19"
}
});
it("should return error when username/password is empty", (done)=> {
done();
// let
})
it("should return object", async () => {
const domainStub = sinon.stub(UserDomain.prototype, 'login');
const result = await UserHandler.login(user);
sinon.assert.calledOnce(domainStub);
domainStub.restore();
})
});
});
如果正常代码(不是上面的单元测试代码)const result = await UserHandler.login(user); 将有一个对象响应,但是当我在 user.test.js 中这样做时它没有得到响应。 result 未定义。
这里是 user_handler 代码
'use strict';
const User = require('./domain');
const login = async (data) => {
const postData = async () => {
const user = new User();
const result = await user.login(data);
return result;
}
const response = await postData();
return response;
}
是我在代码上做错了什么还是缺少某些代码?
如果您确实认为信息不明确,我很抱歉
感谢您的回复
【问题讨论】:
-
试试npmjs.com/package/promise 我更喜欢他们而不是异步等待
-
嗨@BraveButter,实际上由于我缺乏经验,将所有代码从async-await重构为
promise modules需要时间:(。但感谢您之前的建议。非常感谢希望我可以在下一次迭代中使用它
标签: node.js unit-testing async-await sinon stubs