如何模拟库函数(测试 redux action creator)
How to mock library function (testing redux action creator)
我在“Redux-world”中有示例
我有动作创建器(简单功能):
import { v4 } from 'node-uuid';
export const addTodo = (text) => ({
type: 'ADD_TODO',
id: v4(),
text,
});
我已经测试过了 (docs):
import { addTodo } from '../actions'
...
it('should create an action for add todo', () => {
const text = 'test v4 call'
const expectedAction = {
type: 'ADD_TODO',
text,
id: 'fake-v4-id', // ???
}
expect(addTodo(text).toEqual(expectedAction)
})
当然,我有不同的v4 ids:
在我的测试中直接使用 v4(更改:id: 'fake-v4-id' -> id: v4()
)- 没有解决问题。 ID 会有所不同。
我需要什么?模拟,覆盖?或者是其他东西?我该怎么做?
我的测试框架是Mocha,断言库是-Chai。
收件人是:
在.babelrc中设置测试环境(类似这样的东西)
{
"presets": ["es2015", "stage-0", "react", "react-hmre"],
"env":{
"test":{
"plugins": ["rewire"]
}
}
}
安装 babel-cli(如果你还没有的话)
在 package.json 中键入测试命令,如下所示:
NODE_ENV=test babel-node node_modules/.bin/_mocha -r --recursive
* 为什么是_mocha? (link for issue)
好的,设置就绪。现在编辑测试文件:
import { __RewireAPI__, addTodo } from '../actions'
...
describe('Todo actions', () => {
before(() => {
__RewireAPI__.__Rewire__('v4', () => 'fake-v4-id')
})
it('should create an action for add todo', () => {
const text = 'test v4 call'
const expectedAction = {
type: 'ADD_TODO',
text,
id: 'fake-v4-id',
}
expect(addTodo(text)).toEqual(expectedAction)
})
})
运行 npm test
我在“Redux-world”中有示例
我有动作创建器(简单功能):
import { v4 } from 'node-uuid';
export const addTodo = (text) => ({
type: 'ADD_TODO',
id: v4(),
text,
});
我已经测试过了 (docs):
import { addTodo } from '../actions'
...
it('should create an action for add todo', () => {
const text = 'test v4 call'
const expectedAction = {
type: 'ADD_TODO',
text,
id: 'fake-v4-id', // ???
}
expect(addTodo(text).toEqual(expectedAction)
})
当然,我有不同的v4 ids:
在我的测试中直接使用 v4(更改:id: 'fake-v4-id' -> id: v4()
)- 没有解决问题。 ID 会有所不同。
我需要什么?模拟,覆盖?或者是其他东西?我该怎么做?
我的测试框架是Mocha,断言库是-Chai。
收件人是:
在.babelrc中设置测试环境(类似这样的东西)
{ "presets": ["es2015", "stage-0", "react", "react-hmre"], "env":{ "test":{ "plugins": ["rewire"] } } }
安装 babel-cli(如果你还没有的话)
在 package.json 中键入测试命令,如下所示:
NODE_ENV=test babel-node node_modules/.bin/_mocha -r --recursive
* 为什么是_mocha? (link for issue)
好的,设置就绪。现在编辑测试文件:
import { __RewireAPI__, addTodo } from '../actions'
...
describe('Todo actions', () => {
before(() => {
__RewireAPI__.__Rewire__('v4', () => 'fake-v4-id')
})
it('should create an action for add todo', () => {
const text = 'test v4 call'
const expectedAction = {
type: 'ADD_TODO',
text,
id: 'fake-v4-id',
}
expect(addTodo(text)).toEqual(expectedAction)
})
})
运行 npm test