我是Sinon的新手,所以我想检查一个特定的函数是否被调用,这就是我得到的:
terminalController.controller('CashAcceptorController', [
'PaymentService',
'$rootScope',
'$scope',
'PayingInfo',
'$interval',
'$location',
function (PaymentService, $rootScope, $scope, PayingInfo, $interval, $location) {
PaymentService.start();
....
]);
Run Code Online (Sandbox Code Playgroud)
在测试中,我尝试检查在控制器实例化上调用PaymentService.start():
describe('CashAcceptorController', function() {
var PaymentService, rootScope, scope, PayingInfo, $interval, $location;
var mySpy = sinon.spy(PaymentService.start());;
beforeEach(module('eshtaPayTerminalApp.controllers'));
beforeEach(module('eshtaPayTerminalApp.services'));
beforeEach(inject(function($controller,
$rootScope, _PaymentService_, _$interval_, _PayingInfo_) {
$interval = _$interval_;
scope = $rootScope.$new();
rootScope = $rootScope.$new();
PaymentService = _PaymentService_;
PayingInfo = _PayingInfo_;
rootScope.serviceNumber = 'm1';
rootScope.phoneNumber = '05135309';
$controller('CashAcceptorController', {
$rootScope : rootScope,
$scope : scope,
$location : $location,
_PaymentService_ : PaymentService,
_$interval_:$interval,
_PayingInfo_:PayingInfo …Run Code Online (Sandbox Code Playgroud) 所以我有一个这样的 Chai/Mocha/Sinon 测试:
import sinon from 'sinon'
describe(`My Test`, () => {
it(`should track the number of calls`, () => {
function testMe() {
console.log(`test me`)
}
const spy = sinon.spy(testMe)
testMe()
console.log(spy.getCalls())
console.log(spy.callCount)
})
})
Run Code Online (Sandbox Code Playgroud)
测试运行时,会记录以下内容:
test me
[]
0
Run Code Online (Sandbox Code Playgroud)
这令人费解。我究竟做错了什么?
我的代码中有这个功能:
let request = require("request");
let getDrillDownData = function (userId, query, callback) {
query.id = userId;
let urlQuery = buildUrlFromQuery(query);
request.get({
url: urlQuery,
json: true
}, function (error, response, data) {
if (!error && response.statusCode === 200) {
return callback(null, calculateExtraData(data));
} else if (error) {
return callback(error, null);
}
});
};
Run Code Online (Sandbox Code Playgroud)
我希望编写一些单元测试来验证当使用正确的参数调用函数时,它运行正常,如果出现错误,它确实返回了错误
我写了这个单元测试代码:
describe.only('Server Service Unit Test', function(){
var sinon = require('sinon'),
rewire = require('rewire');
var reportService;
var reportData = require('./reportData.json');
beforeEach(function(){
reportService = rewire('../../services/reports.server.service');
});
describe('report methods', function(){ …Run Code Online (Sandbox Code Playgroud) 我有一个类似于下面显示的测试.基本上我想测试特定方法是否会延迟.
以下示例按预期工作,即调用resolve方法并且测试通过:
it(`should delay execution by 1 second`, function () {
const clock = sandbox.useFakeTimers();
const p = new Promise(function (resolve) {
setTimeout(resolve, 1000);
});
clock.tick(1000);
return p;
});
Run Code Online (Sandbox Code Playgroud)
但是,如果我将setTimeout包装在另一个Promise中,则决不会调用该解析:
it(`should delay execution by 1 second`, function () {
const clock = sandbox.useFakeTimers();
const p = Promise.resolve()
.then(() => {
return new Promise(function (resolve) {
setTimeout(resolve, 1000); // resolve never gets called
});
});
clock.tick(1000);
return p;
});
Run Code Online (Sandbox Code Playgroud)
这有什么问题?
我正在使用Sinon 2.1.0和本地的承诺Node 6.9.5.
我正在尝试getAll对此类上的方法进行单元测试:
module.exports = class BookController {
static async getAll() {
return await Book.query()
.eager('reviews');
}
};
Run Code Online (Sandbox Code Playgroud)
Book 是一个异议模型。
我想如何测试它是我想Book.query().eager()用我自己的数据伪造响应,因为我永远无法验证数据库中的内容。要使其成为真正的单元测试,我是否应该只测试该Book.query()方法是否被调用?或者我应该测试返回的数据,因为这是getAll()方法的契约?我真的不确定我应该如何解决这个问题。
在迈向TDD的过程中,我正在使用Mocha,chai和sinon。那里肯定有学习曲线。
我的目标是编写一个测试来验证method4是否已执行。我该如何实现?
//MyData.js
class MyData {
constructor(input) {
this._runMethod4 = input; //true or false
this.underProcessing = this.init();
}
method1() { return this.method2() }
method2() {
if (this._runMethod4) {
return this.method4();
} else {
return this.method3();
}
method4(){
return thirdPartyAPI.getData();
}
method3(){
return someAPI.fetchData();
}
init(){
return this.method1();
}
}
Run Code Online (Sandbox Code Playgroud)
MyData.spec.js
describe('MyData', () => {
it('should execute method 4', function() {
let foo = new MyData(true);
foo.underProcessing.then(()=>{
// How do I verify that method4 was executed ??
expect(foo.method4.callCount).to.equal(1);
});
});
})
Run Code Online (Sandbox Code Playgroud) 我正在使用第三方宁静服务发送短信验证码。我为它写了一个单元测试。但是,我不希望每次运行单元测试时都收到一条消息。
代码是这样的:
const _request = require("request");
_request({
method: "POST",
url: "http://blah.com/json",
form: {
apikey: "blah",
mobile: input.mobilePhoneNumber,
text: `code is: ${verificationCode}`,
}
}, (err, res, body) => {
if (err) {
dbg(`end, output=${err}`)
return reject(new Error("something wrong"))
} else {
dbg(`end, output=${res}`)
return resolve({})
}
})
Run Code Online (Sandbox Code Playgroud)
在测试中我使用 sinon.stub
sinon.stub(request, "post").returns(Promise.resolve({}))
Run Code Online (Sandbox Code Playgroud)
然而,这个存根并没有真正捕捉到请求中的“post”方法。我查看了源代码并尝试了很多方法(比如存根构造函数),但没有一个有效。
想知道有没有人以前试过这个。我应该如何根据要求存根这个 post 方法?
谢谢!
我想要实现的是存根一个将返回某个值的调用。该返回值由传递的参数之一和一个新值组成。
如何获取存根的参数并使用它来形成给定存根调用的返回值
例如
mockDb.query.onCall(0).return(
Tuple(this.args(0), "Some other data");
);
Run Code Online (Sandbox Code Playgroud)
我知道我可以这样做:
sinon.stub(obj, "hello", function (a) {
return a;
});
Run Code Online (Sandbox Code Playgroud)
但是,这适用于整个存根而不是单个存根调用。不幸的是,我无法为不同的调用提供不同的存根,因为我只有一个对象(db 存根)。
我目前正在尝试模拟商店模块中的操作。我似乎无法正确地将其存根,因为我在单元测试中继续收到一条消息,内容是:
[vuex] unknown action type: moduleA/filterData
Run Code Online (Sandbox Code Playgroud)
这是被测组件的简化版本:
项
<template>
<li class="list-item"
@click="toggleActive()">
{{ itemName }}
</li>
</template>
<script>
import store from '../store'
export default {
name: 'item',
props: {
itemName: {
type: String
}
},
data () {
return {
store,
isActive: false
}
},
methods: {
toggleActive () {
this.isActive = !this.isActive;
this.$store.dispatch('moduleA/filterData', { name: itemName } );
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
store.js
import Vue from 'vue'
import Vuex from 'vuex'
import moduleA from './modules/moduleA'
Vue.use(Vuex)
const store = …Run Code Online (Sandbox Code Playgroud) 在我的其余架构中,有一个控制器(处理http请求)和一个服务(提供数据的业务逻辑)。
为了测试控制器,我试图对服务进行存根以提供固定的响应,但是我不明白如何对需要自定义对象作为参数的方法进行存根(如果该参数是文字,那么它将起作用)。
对于自定义对象(Farm),存根不起作用,因为并且我没有从服务方法中收到Promise,这是错误:
TypeError:无法在FarmsController.createFarm(/Users/giovannimarino/Projects/rt-cloud/services/farms/src/farms/farms.controller.ts:17:17)中读取null的'then'属性
farms.controller.spec.ts
describe('FarmsController', () => {
const farmsServiceMock: FarmsService = mock(FarmsService);
let controller: FarmsController;
interface TestData {
farm: Farm;
}
let testData: TestData;
beforeEach(() => {
reset(farmsServiceMock);
const farmsServiceMockInstance: FarmsService = instance(farmsServiceMock);
controller = new FarmsController(farmsServiceMockInstance);
testData = {
farm: <Farm> {
name: 'CattD',
imageUrl: 'img/farm-123b341.png',
lang: 'en',
}
};
});
describe('createFarm function', () => {
describe('success', () => {
it('should return HTTP 200 OK', async () => {
when(farmsServiceMock.createFarm(testData.farm)).thenReturn(Promise.resolve<Farm>(testData.farm));
const pathParameters: PathParameter = {
name: 'CattD', …Run Code Online (Sandbox Code Playgroud) sinon ×10
javascript ×5
mocha.js ×5
unit-testing ×5
node.js ×3
angularjs ×2
chai ×2
mocking ×1
promise ×1
request ×1
settimeout ×1
testing ×1
typescript ×1
vue.js ×1
vuex ×1