How to use sinon mock function

Point1

Today I did a very stupid thing when writing a test. Record it and remind yourself: sinon.stub can mock the method in the test class, but if method A is called by method B in the same class, when B executes, the original method A is still called

1
2
3
4
5
6
7
8
//testForSinon1.js
function test1 () {
console.log('test1');
}

module.exports = {
test1
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//testForSinon2.js
const test1 = require('./testForSinon1');
function test2Inner() {
console.log('_test2Inner');
}

function test2 () {
test1.test1();
test2Inner();
console.log('test2');
}

module.exports = {
test2,
test2Inner
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//sinon.js
const sinon = require('sinon');
const test1 = require('./lib/testForSinon1');
const test2 = require('./lib/testForSinon2');

sinon.stub(test1, 'test1').callsFake(() => {
console.log('test1-stub');
})

sinon.stub(test2, 'test2Inner').callsFake(() => {
console.log('test2Inner-stub');
})


test2.test2Inner();
//test2Inner-stub

test2.test2();
//test1-stub
//_test2Inner
//test2

Point2

If you introduce a method in A through the following method

1
2
// A.js
const { b } = require('./B.js');

Then in the test

1
2
3
4
5
6
7
import B from './B.js';

...
...
...

sinon.stub(B, 'b');

This is actually useless, it still calls the b method itself