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)
版本:“is-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' })
})
尝试使用下面的代码,这里的问题是我们模拟ES6类的方式,基本上,有四种方法来模拟文档中描述的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' })
});
你有没有尝试将__mocks__
(或你的模拟生活的地方)目录添加到roots
的package.json
中?
"jest": {
"roots": [
"<rootDir>/__mocks__",
"<rootDir>/src"
],
...