函数我正在监视,接收对象作为参数.我需要声明函数是使用对象的某些属性调用的.
例如:我的SUT有:
function kaboom() {
fn({
foo: 'foo',
bar: 'bar',
zap: function() { ... },
dap: true
});
}
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我可以这样做:
fnStub = sinon.stub();
kaboom();
expect(fnStub).to.have.been.called;
Run Code Online (Sandbox Code Playgroud)
这是有效的(很高兴知道fn被称为).现在我需要确保已将正确的对象传递给函数.我只关心 foo和bar属性,即我必须为参数的特定属性设置匹配.怎么样?
upd:sinon.match()似乎适用于简单对象.我们提高吧,不是吗?
如果我想将zap函数包含在断言中怎么办?我该如何工作?
我正在尝试使用Sinon来测试看起来有点像这样的JS组件......
import Bootbox from "../helpers/bootbox";
import Guard from "../helpers/guard";
import UrlHelper from "../helpers/url-helper";
export default class DeleteButton {
/**
* Creates an instance of DeleteButton.
*
* @param {object} element The DOM element to make into a delete button.
*
* @memberOf DeleteButton
*/
constructor(element) {
Guard.throwIf(element, "element");
this.deleteUri = element.getAttribute("data-delete-uri") || UrlHelper.current.url().split('?')[0];
this.title = element.getAttribute("data-title") || `Delete the item?`;
this.cancelText = element.getAttribute("data-cancel") || `Cancel`;
this.confirmText = element.getAttribute("data-confirm") || `Remove`;
this.message = element.getAttribute("data-message") || `Do you want to delete the …Run Code Online (Sandbox Code Playgroud) 我在使用sinon和chai在javascript中编写测试时遇到了问题.我正在尝试检查是否在间谍上调用了一个函数并获得"错误:无效的Chai属性:calledOnce"
我在另一个具有相同测试依赖性的项目中做同样的事情没有任何问题......
var udpSocketStub = this.sandbox.spy(udpSocket, 'send');
expect(udpSocketStub).calledOnce; // SHOULD FAIL
"dependencies": {
"body-parser": "~1.17.1",
"bootstrap": "^4.0.0-alpha.6",
"chai": "^4.1.0",
"co-mocha": "^1.2.0",
"cookie-parser": "~1.4.3",
"debug": "~2.6.3",
"express": "~4.15.2",
"jquery": "^3.2.1",
"mocha": "^3.4.2",
"morgan": "~1.8.1",
"node-compass": "0.2.3",
"pug": "^2.0.0-rc.1",
"serve-favicon": "~2.4.2",
"sinon": "^2.3.8",
"sinon-chai": "^2.12.0"
}
Run Code Online (Sandbox Code Playgroud) 任何人都可以帮我测试以下功能
function onload(cb){
const image = 'http://placehold.it/350x150'
const img = new Image()
img.src = image
img.onload = () => {
cb()
}
}
Run Code Online (Sandbox Code Playgroud)
在我的测试文件Image中可以通过jsdom获得.我想我可以测试那个cb叫做一次
我一直在学习 Sinon JS 进行单元测试,并且我正在尝试让这个示例代码正常工作。我创建了一个简单的“外部”库:
class MyLib {
simpleMethod () {
return 'some response';
}
static handler() {
const myLib = new MyLib();
myLib.simpleMethod();
}
}
module.exports = MyLib;
Run Code Online (Sandbox Code Playgroud)
然后,我有一个简单的测试套件:
const chai = require('chai');
const sinon = require('sinon');
const MyLib = require('./my-lib');
describe ('sinon example tests', () => {
it ('should call simpleMethod once', () => {
let stubInstance = sinon.stub(MyLib, 'simpleMethod');
MyLib.handler();
sinon.assert.calledOnce(stubInstance);
});
});
Run Code Online (Sandbox Code Playgroud)
但我返回错误“AssertError:预期存根将被调用一次,但被调用 0 次”。我知道这可能是显而易见的,但为什么simpleMethod没有被调用?
Sinon 似乎没有从导入的文件中存根方法。这与导出常量有关吗?
我在 console.log 中看到“已收到原始消息”。
Main.js
import * as otherActions from 'filters/actions/Other.actions';
describe('filter actions', () => {
it('should log STUBBED MESSAGE', () => {
sinon.stub(otherActions, 'logMessage').callsFake(m => console.log('STUBBED Message'));
const compiled = otherActions.doSomethingAndLogMessage(5, 5);
compiled(message => console.log(`RECEIVED ${message}`), () => {});
});
});
Run Code Online (Sandbox Code Playgroud)
其他.actions.js
export const logMessage = () => console.log("ORIGINAL MESSAGE");
export const doSomethingAndLogMessage = (categoryId, size) => (dispatch, getState) => {
dispatch(logMessage());
};
Run Code Online (Sandbox Code Playgroud) 似乎有很多不同的方法可以做到这一点,但我试图只使用 sinon、sinon-test、chai/mocha、axios、httpmock 模块。我无法成功模拟使用 axios 进行的 GET 调用。我希望能够模拟来自该 axios 调用的响应,因此单元测试实际上不必发出外部 API 请求。
我尝试通过创建沙箱来设置基本单元测试,并使用 sinon 存根设置 GET 调用并指定预期响应。我不熟悉 JavaScript 和 NodeJS。
// Main class (filename: info.js)
function GetInfo(req, res) {
axios.get(<url>).then(z => res.send(z.data));
}
// Test class (filename: info.test.js)
it ("should return info", () => {
const expectedResponse = "hello!";
const res = sinon.spy();
const aStub = sinon.stub(axios, "get").resolves(Promise.resolve(expectedResponse));
const req = httpMock.createRequest({method:"get", url:"/GetInfo"});
info.GetInfo(req, res);
// At this point, I need to evaluate the response received (which should be expectedResponse)
assert(res.data, …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试一个调用 module 的函数cors。我想测试那个cors会被调用。为此,我必须存根/模拟它。
这是函数 cors.js
const cors = require("cors");
const setCors = () => cors({origin: 'http//localhost:3000'});
module.exports = { setCors }
Run Code Online (Sandbox Code Playgroud)
我测试此类功能的想法类似于
cors.test.js
describe("setCors", () => {
it("should call cors", () => {
sinon.stub(cors)
setCors();
expect(cors).to.have.been.calledOnce;
});
});
Run Code Online (Sandbox Code Playgroud)
知道如何存根 npm 模块吗?
所以我有一个文件,user-database看起来像这样:
export function foo(id: number): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
findSomething(id)
.then((data) => {
//do something with data
})
}
}
export function findSomething(id: number): Promise<Object> {
return new Promise<Object> ((resolve, reject) => {
let query = 'SELECT * FROM user';
db.executeQuery(query);
.then(data) => {
if(data.length < 1) { reject(new Error('whoops')); }
resolve(data);
}, (err) => {
reject(err);
})
})
}
Run Code Online (Sandbox Code Playgroud)
所以我正在使用Sinon编写单元测试用于外部函数,foo因此我想将它调用的函数存根findSomething.我这样做如下:
import * as user_db from '../../src/user-database';
describe('POST /someEndpoint', () …Run Code Online (Sandbox Code Playgroud) 我需要测试这个功能:
//user.js
function getUser(req,res,next){
helper.get_user(param1, param2, (err,file)=>{
if (err)
return next(err);}
Run Code Online (Sandbox Code Playgroud)
我的测试功能:
it ("failed - helper.get_user throws error",sinon.test(function () {
var req,res;
var get_user = this.stub(helper,"get_user")
get_user.yields(new Error("message"));
var next = sinon.spy(next);
user.get_user(req,res,next);
expect(next).to.have.been.calledWith(new Error("other message"));
}))
Run Code Online (Sandbox Code Playgroud)
对于我的断言,我正在使用sinon-chai语法.虽然我希望它失败,但这个测试正在通过.因为我的代码不会抛出带错误的消息.
我如何测试错误是否与正确的消息一起被抛出?
sinon-chai ×10
sinon ×9
javascript ×7
node.js ×4
unit-testing ×4
axios ×1
chai ×1
jsdom ×1
mocha.js ×1
mocking ×1
typescript ×1