test framework /mock up / bdd / tdd / node에서 tdd / test unittest / test case
mocha, chai, sinon
mocha with typescript
typescript 와 mocha 를 이용하는 방법은 아래 링크를 참고하자.
- Write tests for TypeScript projects with mocha and chai — in TypeScript! | by Sudarsan Balaji | The Journal of Artful Development: ts-node 를 이용해서 실행한다.
npm install mocha chai ts-node --save-dev
mocha --recursive -r ts-node/register ./src/ts/test/**/*.test.ts
cheatsheets
sinon
stub 는 type 들을 다 맞춰줘야 한다. 그래서 간단히 만들때는 fake 가 더 낫긴 하다. 하지만 확실히 정확한 test 를 위해서는 type 을 맞추는 stub 가 나을 수 있다.
ts-node + mocha 의 debugging 을 위한 vscode launch.js
trace는 진단로그(diagnostic log) 를 찍어준다.
sourceMaps 은 sourceMap 이 있는 js 인 경우 sourceMap 을 사용한다.
2개의 옵션이 없어도 ts 에 대한 debug 가 잡히는 것 같다.
{
"version": "0.2.0",
"configurations": [
{
"args": [
"-u",
"bdd",
"--timeout",
"999999",
"--colors",
"-r",
"ts-node/register",
"--recursive",
"${file}"
],
"internalConsoleOptions": "openOnSessionStart",
"name": "Mocha Tests Current File",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"request": "launch",
"skipFiles": [
"/**"
],
"type": "pwa-node",
"trace": true,
"sourceMaps": true,
}
]
}
unittest examples
특정 object.method 안에서 "다른 object.method" 의 parameter 를 확인하기 위한 방법
export class MyRequest {
host = 'bunjang.co.kr';
version = 4;
constructor() {
}
async retrieve() {
const customAxios =
this._getCustomAxios();
// const now = new Date();
const utcNow = moment().utc();
// ex: 2020918080254
const requestId = utcNow.format("YYYYMDDHHmss");
const response = await customAxios.get(`/api/1/product/${startPid}/detail_info.json`, {
params: {
version: this.version,
// get random 7 digit which starts with 1
stat_uid: this._getStatUid()
}
})
}
_getCustomAxios() {
const customAxios = axios.create({
baseURL: `https://test/`
})
return customAxios;
}
}
import sinon, { spy } from 'sinon';
import { expect } from 'chai';
import { AxiosResponse } from 'axios';
describe('Reuquest', () => {
it('should retrieve', async () => {
const spyGet = spy((url: string, param: any): AxiosResponse => {
return {
data: {
list: [],
},
status: 200,
statusText: "",
headers: {},
config: {},
};
});
const fakeGet = sinon.fake.returns({
get: spyGet
})
const myReq = new MyRequest();
sinon.replace(
myReq,
'_getCustomAxios',
fakeGet);
await myReq.retrieve();
sinon.restore();
// get 을 1번째 call 했을 때의 argument중 2번째(args[1])
const actualParam = { ...spyGet.getCall(0).args[1].params };
expect(actualParam).to.deep.equal({
test1: 'mytest',
version: 'mytest-ver',
});
});
});
댓글 없음:
댓글 쓰기