ffMathy / FluffySpoon.JavaScript.Testing.Faking

An NSubstitute port to TypeScript called substitute.js.
MIT License
203 stars 22 forks source link

Partial mock `this` in a mimick function is not the mock's `this` #17

Closed jasperblues closed 5 years ago

jasperblues commented 5 years ago

Steps to Repro:

export interface Client {

    authorize(correlationId: string): Promise<string>;

    sendBuyerData(buyerId:string, correlationId: string): Promise<void>;

}

*Mock the authorize method:

 const partialClient = Substitute.for<Client>();
 partialClient.sendBuyerData(Arg.all()).mimicks(client.sendBuyerData);
 partialClient.authorize(Arg.any()).returns(Promise.resolve(uuid()));

Test:

 public async sendBuyerData(buyerId: string, correlationId: string): Promise<void> {

        const token = await this.authorize(correlationId);
        //etc 

Expected:

This is the mock's this.

Actual:

This points to the function. A class's methods can't call other methods.

ffMathy commented 5 years ago

I'm not sure what you mean here. Can you elaborate - perhaps make a full reproducable example, throwing an error?

jasperblues commented 5 years ago

I mean when you partially mock a class, the concrete method should be able to call other methods in the mock.

Expected:

Actual:

Error: Function does not have a property named methodName

Example:

class ClientDefaultImpl {

public async authorize(token: string): Promise<string> {} //THIS IS MOCKED 

public async sendBuyerData(buyerId: BuyerModel.Buyer['id'], correlationId: string): Promise<void> {

        logger.info(`Posting Buyer '${buyerId} to Unipay.'`);

        const token = await this.authorize(correlationId);   <---- This fails on a partial mock because `this` is not bound to the mock. 
        const unipayCustomerUrl = `${this.baseUrl}/api/customers`;

        // Fetch the buyer
        // etc more implementation

}
jasperblues commented 5 years ago

Please reopen this issue, it is an essential feature. I can send a pull request. Let me know if the example is not clear.

ffMathy commented 5 years ago

A PR would be absolutely fantastic.

I'm still not sure what you mean though.

Can you provide an example with a unit test that fails?

jasperblues commented 5 years ago

OK, let's establish the problem with an example first. Stay tuned . . (it might take a few days, under the hammer here a bit, a the moment).

ffMathy commented 5 years ago

Closing until I hear more. Looking forward to it <3