Jest没有提供我的手动模拟。一切似乎都在正确的目录中。我错过了什么?
的src /适配器/ __嘲笑__ / Foo.js
const spy = jest.genMockFromModule('../Foo')
function doStuff() {
return { source: 'mock' }
}
spy.doStuff = doStuff
module.exports = spy
的src /适配器/ Foo.js
class Foo {
doStuff() {
return { source: 'real' }
}
}
module.exports = Foo
的src /适配器/ __测试__ / Foo.js
const Foo = require('../Foo')
test('Foo', () => {
const foo = new Foo()
expect(foo.doStuff()).toEqual({ source: 'mock' })
})
测试输出:
expect(received).toEqual(expected)
Expected value to equal:
{"source": "mock"}
Received:
{"source": "real"}
Difference:
- Expected
+ Received
Object {
- "source": "mock",
+ "source": "real",
}
3 | test('Foo', () => {
4 | const foo = new Foo()
> 5 | expect(foo.doStuff()).toEqual({ source: 'mock' })
6 | })
7 |
at Object.<anonymous>.test (adapters/__tests__/Foo.js:5:25)
Jest Version:“jest-cli”:“^ 23.0.0-alpha.0”
远射,试过这个,但没有奏效。没有找到模拟,只是在调用doStuff()
时给了我未定义的内容的src /适配器/ __测试__ / Foo.js
//TREID this but didn't work
jest.mock('../Foo')
const Foo = require('../Foo')
test('Foo', () => {
const foo = new Foo()
expect(foo.doStuff()).toEqual({ source: 'mock' })
})
答案 0 :(得分:1)
尝试使用下面的代码,问题是我们模拟ES6类的方式,基本上,有4种方法来模拟class
,如文档中所述
https://facebook.github.io/jest/docs/en/es6-class-mocks.html
<强>的src /适配器/ __嘲笑__ / Foo.js 强>
const mock = jest.fn().mockImplementation(()=>{
return {
doStuff: jest.fn(()=>({source: 'mock'}))
}
});
module.exports = mock;
<强>的src /适配器/ __测试__ / Foo.js 强>
jest.mock('../Foo');
const Foo = require('../Foo');
test('Foo', () => {
const foo = new Foo();
expect(foo.doStuff()).toEqual({ source: 'mock' })
});
<强>(或)强>
内联模拟也可以使用
<强>的src /适配器/ __测试__ / Foo.js 强>
jest.mock('../Foo', () => {
return jest.fn().mockImplementation(() => {
return {
doStuff: jest.fn(() => ({ source: 'mock' }))
}
});
});
const Foo = require('../Foo');
test('Foo', () => {
const foo = new Foo();
expect(foo.doStuff()).toEqual({ source: 'mock' })
});
答案 1 :(得分:0)
您是否尝试将__mocks__
(或您的模拟现场)目录添加到roots
中的package.json
?
"jest": {
"roots": [
"<rootDir>/__mocks__",
"<rootDir>/src"
],
...